Module: Deterministic::Monad
Defined Under Namespace
Classes: NotMonadError
Instance Method Summary collapse
-
#==(other) ⇒ Object
Two monads are equivalent if they are of the same type and when their values are equal.
-
#bind(proc = nil, &block) ⇒ Object
(also: #>>=)
- The monad: takes a function which returns a monad (of the same type), applies the function bind
-
(a -> Mb) -> M a -> M b the self.class, i.e.
-
#fmap(proc = nil, &block) ⇒ Object
- The functor: takes a function (a -> b) and applies it to the inner value of the monad (Ma), boxes it back to the same monad (Mb) fmap
-
(a -> b) -> M a -> M b.
- #initialize(value) ⇒ Object
-
#inspect ⇒ Object
Return the string representation of the Monad.
- #join(value) ⇒ Object
- #to_s ⇒ Object
-
#value ⇒ Object
- Get the underlying value, return in Haskell return
-
M a -> a.
Instance Method Details
#==(other) ⇒ Object
Two monads are equivalent if they are of the same type and when their values are equal
51 52 53 54 |
# File 'lib/deterministic/monad.rb', line 51 def ==(other) return false unless other.is_a? self.class @value == other.instance_variable_get(:@value) end |
#bind(proc = nil, &block) ⇒ Object Also known as: >>=
The monad: takes a function which returns a monad (of the same type), applies the function
- bind
-
(a -> Mb) -> M a -> M b
the self.class, i.e. the containing monad is passed as a second (optional) arg to the function
27 28 29 30 31 32 |
# File 'lib/deterministic/monad.rb', line 27 def bind(proc=nil, &block) (proc || block).call(value).tap do |result| parent = self.class.superclass === Object ? self.class : self.class.superclass raise NotMonadError, "Expected #{result.inspect} to be an #{parent}" unless result.is_a? parent end end |
#fmap(proc = nil, &block) ⇒ Object
The functor: takes a function (a -> b) and applies it to the inner value of the monad (Ma), boxes it back to the same monad (Mb)
- fmap
-
(a -> b) -> M a -> M b
19 20 21 22 |
# File 'lib/deterministic/monad.rb', line 19 def fmap(proc=nil, &block) result = (proc || block).call(value) self.class.new(result) end |
#initialize(value) ⇒ Object
5 6 7 |
# File 'lib/deterministic/monad.rb', line 5 def initialize(value) @value = join(value) end |
#inspect ⇒ Object
Return the string representation of the Monad
57 58 59 60 |
# File 'lib/deterministic/monad.rb', line 57 def inspect name = self.class.name.split("::")[-1] "#{name}(#{value})" end |
#join(value) ⇒ Object
11 12 13 14 |
# File 'lib/deterministic/monad.rb', line 11 def join(value) if value.is_a? self.class then value.value else value end end |
#to_s ⇒ Object
41 42 43 |
# File 'lib/deterministic/monad.rb', line 41 def to_s value.to_s end |
#value ⇒ Object
Get the underlying value, return in Haskell
- return
-
M a -> a
37 38 39 |
# File 'lib/deterministic/monad.rb', line 37 def value @value end |