Class: TAlgebra::Monad::Maybe
- Inherits:
-
Object
- Object
- TAlgebra::Monad::Maybe
- Includes:
- SingleValued
- Defined in:
- lib/t_algebra/monad/maybe.rb
Constant Summary collapse
- NOTHING =
:nothing
- JUST =
:just
Class Method Summary collapse
Instance Method Summary collapse
- #==(other) ⇒ Object
- #bind {|value| ... } ⇒ Object
- #fetch(key) ⇒ Object
- #fmap(&block) ⇒ Object
- #from_maybe ⇒ Object
- #from_maybe! ⇒ Object
- #just? ⇒ Boolean
- #nothing? ⇒ Boolean
- #to_obj ⇒ Object
Methods included from SingleValued
Class Method Details
.nothing ⇒ Object
15 16 17 |
# File 'lib/t_algebra/monad/maybe.rb', line 15 def nothing new(is: NOTHING) end |
.pure(value) ⇒ Object Also known as: just
10 11 12 |
# File 'lib/t_algebra/monad/maybe.rb', line 10 def pure(value) new(is: JUST, value: value) end |
.to_maybe(value_or_nil) ⇒ Object
19 20 21 |
# File 'lib/t_algebra/monad/maybe.rb', line 19 def to_maybe(value_or_nil) value_or_nil.nil? ? nothing : pure(value_or_nil) end |
Instance Method Details
#==(other) ⇒ Object
60 61 62 |
# File 'lib/t_algebra/monad/maybe.rb', line 60 def ==(other) to_obj == other.to_obj end |
#bind {|value| ... } ⇒ Object
29 30 31 32 |
# File 'lib/t_algebra/monad/maybe.rb', line 29 def bind(&block) return dup if nothing? || !block yield value end |
#fetch(key) ⇒ Object
52 53 54 55 56 57 58 |
# File 'lib/t_algebra/monad/maybe.rb', line 52 def fetch(key) bind do |o| self.class.to_maybe( o.respond_to?(:[]) ? o[key] : o.send(key) ) end end |
#fmap(&block) ⇒ Object
24 25 26 27 |
# File 'lib/t_algebra/monad/maybe.rb', line 24 def fmap(&block) return dup if nothing? || !block self.class.just(yield(value)) end |
#from_maybe ⇒ Object
46 47 48 49 50 |
# File 'lib/t_algebra/monad/maybe.rb', line 46 def from_maybe raise UseError.new("#from_maybe called without block") unless block_given? return yield if nothing? value end |
#from_maybe! ⇒ Object
42 43 44 |
# File 'lib/t_algebra/monad/maybe.rb', line 42 def from_maybe! from_maybe { |e| raise UnsafeError.new("#from_maybe! exception. #{e}") } end |
#nothing? ⇒ Boolean
34 35 36 |
# File 'lib/t_algebra/monad/maybe.rb', line 34 def nothing? is == NOTHING end |
#to_obj ⇒ Object
64 65 66 |
# File 'lib/t_algebra/monad/maybe.rb', line 64 def to_obj {is.to_s => value, :class => self.class.name} end |