Module: Maybe

Includes:
Control::Monad, UnionType
Included in:
Just, Nothing
Defined in:
lib/data.maybe.rb

Overview

‘Either a b` is either `Left a` or `Right b`

Instance Method Summary collapse

Methods included from Helper

#alias_names

Methods included from Control::Monad

#>>

Methods included from Control::Applicative

#apply

Instance Method Details

#flat_mapEither

it override Monad#flat_map, as Haskell’s ‘>flat_map` method if it’s Right, pass the value to #flat_map’s block, and flat the result of the block.

when it’s Left, do nothing “‘ ruby expect(Right.new(1).flat_map { |x| Left.new } ).to eq(Left.new) expect(Left.new(1).flat_map { |x| Left.new } ).to eq(Left.new(1)) “`

Returns:

  • (Either)


52
53
54
55
56
57
58
59
# File 'lib/data.maybe.rb', line 52

def flat_map
  case self
  when Just
    yield @v
  else
    self
  end
end

#get_or_else(e) ⇒ Object

get value ‘a` out from `Right a`, otherwise return `e`



17
18
19
20
21
22
23
24
# File 'lib/data.maybe.rb', line 17

def get_or_else(e)
  case self
  when Just
    @v
  else
    e
  end
end

#initialize(v = nil) ⇒ Either

Either only contain one value @v

Returns:

  • (Either)


12
13
14
# File 'lib/data.maybe.rb', line 12

def initialize(v = nil)
  @v = v
end

#mapEither

overide of Functor’s ‘fmap`, apply function on `Right a`’s value ‘a`, do nothing if it’s ‘Left e`

“‘ ruby

Right.new(1).map {|x| x + 1} # => #<Right value=2>
Left.new(1).map {|x| x + 1} # => #<Left value=1>

“‘

Returns:

  • (Either)


33
34
35
36
37
38
39
40
# File 'lib/data.maybe.rb', line 33

def map
  case self
  when Just
    Just.new(yield @v)
  else
    self
  end
end

#to_sString Also known as: inspect

Returns:

  • (String)


81
82
83
84
85
86
87
88
# File 'lib/data.maybe.rb', line 81

def to_s
  case self
  when Just
    "#<Just #{@v}>"
  else
    '#<Nothing>'
  end
end

#when(what) ⇒ Either

similar to Scala’s ‘match` for case class

will pattern match the value out and pass to matched lambda

“‘ ruby Right.new(1).when(->x{x+1 }) # => 2 Right.new(1).when(->x{x+1) # => nil Right.new(1).when(->x{x+1, _: ->xx-1 }) # => 0 “`

Returns:

  • (Either)


71
72
73
74
75
76
77
78
# File 'lib/data.maybe.rb', line 71

def when(what)
  current_class = self.class.to_s.to_sym
  if what.include? current_class
    what[current_class].call(@v)
  elsif what.include? :_
    what[:_].call(@v)
  end
end