Class: Mon::Monad::Some

Inherits:
Maybe show all
Defined in:
lib/monads/maybe.rb

Overview

The Some class represents a value that is NOT null/false

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Maybe

#method_missing, #valid?

Methods included from ChainableMonad

#_, #coerce, #method_missing, #respond_to?

Constructor Details

#initialize(obj) ⇒ Some

Returns a new instance of Some.



62
63
64
65
# File 'lib/monads/maybe.rb', line 62

def initialize(obj)
  @obj = obj
  super()
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Mon::Monad::Maybe

Class Method Details

.[](obj) ⇒ Object

Wrap an object. You probably want Maybe, but there’s a slight difference: Maybe # ==> None Some # ==> Some



70
71
72
73
74
75
76
# File 'lib/monads/maybe.rb', line 70

def self.[](obj)
  if obj.is_a? None
    obj
  else
    Some.new(obj)
  end
end

Instance Method Details

#==(o) ⇒ Object



127
128
129
# File 'lib/monads/maybe.rb', line 127

def ==(o)
  eql?(o)
end

#bind(&fun) ⇒ Object

If we’re wrapping a value, apply fun() to it. Otherwise, None stays None.



104
105
106
107
108
109
110
111
112
113
# File 'lib/monads/maybe.rb', line 104

def bind &fun
  o = fun.call(@obj)
  if o.is_a? Maybe
    o
  elsif o
    Some[o]
  else
    None::none
  end
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


119
120
121
122
123
124
125
# File 'lib/monads/maybe.rb', line 119

def eql?(other)
  if other.is_a? Some
    @obj == other.unwrap
  else
    @obj == other
  end
end

#equal?(o) ⇒ Boolean

Returns:

  • (Boolean)


131
132
133
# File 'lib/monads/maybe.rb', line 131

def equal?(o)
  eql?(o)
end

#or(obj = nil, &f) ⇒ Object

If there’s a wrapped value, return it. Otherwise, either return the supplied object, or execute the supplied block. Eg: <tt>Maybe.or(5) # ==> 1 Maybe.or(5) # ==> 5 Maybe.or { throw Exception.new(“…”) } # ==> Exception!



93
94
95
# File 'lib/monads/maybe.rb', line 93

def or obj = nil, &f
  @obj
end

#orFail(msg = nil) ⇒ Object

Get the value, or throw an exception (using the optional supplied msg) if it’s empty



98
99
100
101
# File 'lib/monads/maybe.rb', line 98

def orFail(msg = nil)
  msg = "No such value!" if msg.nil?
  self::or { throw RuntimeError.new(msg) }
end

#to_sObject



115
116
117
# File 'lib/monads/maybe.rb', line 115

def to_s
  "Some[#{ @obj.to_s }]"
end