RSpec-ified
[ruby-do-notation.git] / lib / maybe.rb
blob306ed2fcbf5974b6192bd172e1c55a40a6dc884b
1 class Maybe < Monad
2   class << self
3     alias_method :nothing, :new
4     alias_method :just, :new
5     alias_method :unit, :just
6   end
7   
8   attr_accessor :value, :nothing
9   
10   def initialize *args
11     if args.empty?
12       @nothing = true
13     else
14       @value = args.shift
15     end
16   end
17   
18   def ==(m)
19     m.is_a? Maybe and ((nothing and m.nothing) or (value = m.value))
20   end
21     
22   def bind &f
23     if self.nothing
24       self
25     else
26       f.call(self.value)
27     end
28   end
29   
30   def to_s
31     if @nothing
32       "nothing"
33     else
34       "just(#{@value})"
35     end
36   end
37 end