Module: Monadic::Monad

Included in:
Either, Maybe
Defined in:
lib/monadic/monad.rb

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Object


51
52
53
54
# File 'lib/monadic/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

Allows priviledged access to the inner value of the Monad from within the block


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

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


21
22
23
# File 'lib/monadic/monad.rb', line 21

def fetch
  @value
end

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


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

def flat_map(proc = nil, &block)
  fail "Underlying value does not respond to #map" unless @value.respond_to? :map
  func = (proc || block)
  return self.class.unit(@value.map {|v| func.call(v) }) if @value.respond_to? :map
end

#initialize(value) ⇒ Object


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

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

#join(value) ⇒ Object

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


14
15
16
17
# File 'lib/monadic/monad.rb', line 14

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. (A -> B) -> M -> M


28
29
30
31
# File 'lib/monadic/monad.rb', line 28

def map(proc = nil, &block)
  func = (proc || block)
  return self.class.unit(func.call(@value))
end

#to_aryArray Also known as: to_a

Returns a with the values inside the monad.

Returns:

  • (Array)

    a with the values inside the monad


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

def to_ary
  Array(@value)
end

#to_sObject

Return the string representation of the Monad


46
47
48
49
# File 'lib/monadic/monad.rb', line 46

def to_s
  pretty_class_name = self.class.name.split('::')[-1]
  "#{pretty_class_name}(#{self.fetch.inspect})"
end