Module: Maybe
Overview
Maybe is a union type that is expressed in terms of Nothing and Just. It is useful for gracefully handling potentially null values:
Class Method Summary collapse
- .from_nullable(value) ⇒ Object
- .Just(value) ⇒ Object
- .lift(f, fst, *rst) ⇒ Object
- .Nothing ⇒ Object
- .of(value) ⇒ Object
- .zip(fst, snd, *rest) ⇒ Object
Instance Method Summary collapse
-
#Proc ⇒ Just<Any>, Nothing
Takes a function and a set of Maybes, and attempts to apply the function and return the result wrapped in a Maybe.
Class Method Details
.from_nullable(value) ⇒ Object
101 102 103 |
# File 'lib/maybe.rb', line 101 def self.from_nullable(value) value.nil? ? Nothing.instance : Just.new(value) end |
.Just(value) ⇒ Object
66 67 68 |
# File 'lib/maybe.rb', line 66 def self.Just(value) Just.new(value) end |
.lift(f, fst, *rst) ⇒ Object
170 171 172 173 174 175 176 177 178 |
# File 'lib/maybe.rb', line 170 def self.lift(f, fst, *rst) [fst, *rst] .reduce(Just([])) {|accum, maybe| accum.flat_map {|accum_| maybe.map {|maybe_| accum_ + [maybe_] } } } .ap( Just(->(args){ f.call(*args) }) ) end |
.Nothing ⇒ Object
53 54 55 |
# File 'lib/maybe.rb', line 53 def self.Nothing Nothing.instance end |
.of(value) ⇒ Object
79 80 81 |
# File 'lib/maybe.rb', line 79 def self.of(value) Just.new(value) end |
.zip(fst, snd, *rest) ⇒ Object
131 132 133 134 135 136 137 |
# File 'lib/maybe.rb', line 131 def self.zip(fst, snd, *rest) [fst, snd, *rest].reduce(Just([])) do |accum, maybe| accum.flat_map do |accum_| maybe.map {|maybe_| accum_ + [maybe_] } end end end |