Module: Maybe
Overview
‘Either a b` is either `Left a` or `Right b`
Instance Method Summary collapse
-
#flat_map ⇒ Either
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.
-
#get_or_else(e) ⇒ Object
get value ‘a` out from `Right a`, otherwise return `e`.
-
#initialize(v = nil) ⇒ Either
Either only contain one value @v.
-
#map ⇒ Either
overide of Functor’s ‘fmap`, apply function on `Right a`’s value ‘a`, do nothing if it’s ‘Left e`.
- #to_s ⇒ String (also: #inspect)
-
#when(what) ⇒ Either
similar to Scala’s ‘match` for case class.
Methods included from Helper
Methods included from Control::Monad
Methods included from Control::Applicative
Instance Method Details
#flat_map ⇒ Either
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)) “`
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
12 13 14 |
# File 'lib/data.maybe.rb', line 12 def initialize(v = nil) @v = v end |
#map ⇒ Either
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>
“‘
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_s ⇒ String Also known as: inspect
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 “`
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 |