Class: Maybe

Inherits:
Object
  • Object
show all
Defined in:
lib/maybe.rb

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Maybe

Returns a new instance of Maybe.



9
10
11
12
# File 'lib/maybe.rb', line 9

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/maybe.rb', line 14

def method_missing(method_name, *args)
  self.fmap do |value|
    value.send(method_name,*args) do |*block_args|
      yield(*block_args) if block_given?
    end
  end
end

Instance Method Details

#fmapObject

Given that the value is of type A takes a function from A->B and returns M (a monad with a value of type B)



40
41
42
43
44
45
46
# File 'lib/maybe.rb', line 40

def fmap
  if(@value==nil)
    self
  else
    Maybe.new(yield(@value))
  end
end

#joinObject



52
53
54
55
56
57
# File 'lib/maybe.rb', line 52

def join
  if(@value.is_a?(Maybe))
    @value = value.value
  end
  self
end

#nil?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/maybe.rb', line 48

def nil?
  @value==nil
end

#passObject

Given that the value is of type A takes a function from A->M and returns M (a monad with a value of type B)



33
34
35
# File 'lib/maybe.rb', line 33

def pass
  fmap {|*block_args| yield(*block_args)}.join
end

#value(value_if_nil = nil) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/maybe.rb', line 22

def value(value_if_nil=nil)
  if(value_if_nil!=nil && @value==nil)
    value_if_nil
  else
    @value
  end
end

#value=(value) ⇒ Object

for testing purposes



60
61
62
# File 'lib/maybe.rb', line 60

def value=(value)
  @value = value
end