Class: Monadic::Monad

Inherits:
Object show all
Defined in:
lib/monadic/monad.rb

Direct Known Subclasses

Either, Maybe

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Monad

Returns a new instance of Monad.



7
8
9
# File 'lib/monadic/monad.rb', line 7

def initialize(value)
  @value = join(value)
end

Class Method Details

.unit(value) ⇒ Object



3
4
5
# File 'lib/monadic/monad.rb', line 3

def self.unit(value)
  new(value)
end

Instance Method Details

#==(other) ⇒ Object



44
45
46
47
# File 'lib/monadic/monad.rb', line 44

def ==(other)
  return false unless other.is_a? self.class
  @value == other.instance_variable_get(:@value)
end

#bind(proc = nil, &block) ⇒ Object



11
12
13
# File 'lib/monadic/monad.rb', line 11

def bind(proc=nil, &block)
  (proc || block).call(@value)
end

#fetchObject Also known as: _

Unwraps the the Monad

Returns:

  • the value contained in the monad



24
25
26
# File 'lib/monadic/monad.rb', line 24

def fetch
  @value
end

#join(value) ⇒ Object

If the passed value is monad already, get the value to avoid nesting M[M] is equivalent to M



17
18
19
20
# File 'lib/monadic/monad.rb', line 17

def join(value)
  if value.is_a? self.class then value.fetch
  else value end
end

#map(proc = nil, &block) ⇒ Object

A functor applying the proc or block on the boxed ‘value` and returning the Monad with the transformed values. If the underlying `value` is an `Enumerable`, the map is applied on each element of the collection. (A -> B) -> M -> M



32
33
34
35
36
# File 'lib/monadic/monad.rb', line 32

def map(proc = nil, &block)
  func = (proc || block)
  return self.class.unit(@value.map {|v| func.call(v) }) if @value.is_a?(::Enumerable)
  return self.class.unit(func.call(@value))
end

#to_sObject

Return the string representation of the Monad



39
40
41
42
# File 'lib/monadic/monad.rb', line 39

def to_s
  pretty_class_name = self.class.name.split('::')[-1]
  "#{pretty_class_name}(#{@value.nil? ? 'nil' : @value.to_s})"
end