Class: Mon::Monad::Pending

Inherits:
Lazy show all
Defined in:
lib/monads/lazy.rb

Overview

Pending represents a Lazy value with pending operations. Unwrapping or finalizing with trigger said pending operations.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Lazy

[], valid?

Methods included from ChainableMonad

#coerce, #method_missing, #respond_to?

Constructor Details

#initialize(fun, target = nil) ⇒ Pending

Returns a new instance of Pending.



132
133
134
135
136
137
138
# File 'lib/monads/lazy.rb', line 132

def initialize(fun, target = nil)
  case fun.arity
  when 1 then @fun = lambda { fun.call(target.unwrap) }
  when 0 then @fun = fun
  else raise ArgumentError.new("Bad function passed to #{ self }")
  end
end

Dynamic Method Handling

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

Class Method Details

.eventually(fun, args) ⇒ Object

Perform an operation, if necessary: Lazy.eventually { 10 * 10 } Or: Lazy.eventually(10) { |n| n * 10 }



170
171
172
# File 'lib/monads/lazy.rb', line 170

def self::eventually fun, args
  Pending.new(lambda { fun.call(*args.map { |v| (v.is_a? Lazy) ? v.unwrap : v }) })
end

Instance Method Details

#==(o) ⇒ Object



191
192
193
# File 'lib/monads/lazy.rb', line 191

def == o
  eql? o
end

#_Object

Alias for #unwrap



162
163
164
# File 'lib/monads/lazy.rb', line 162

def _
  unwrap
end

#_canBind?(name) ⇒ Boolean

Returns:

  • (Boolean)


145
146
147
# File 'lib/monads/lazy.rb', line 145

def _canBind?(name)
  true
end

#bind(&fun) ⇒ Object

Add an operation to be performed on the wrapped value, only if necessary



141
142
143
# File 'lib/monads/lazy.rb', line 141

def bind(&fun)
  Pending::eventually(fun, [self])
end

#eql?(o) ⇒ Boolean

Returns:

  • (Boolean)


178
179
180
181
182
183
184
185
# File 'lib/monads/lazy.rb', line 178

def eql? o
  # Time to collapse
  if o.is_a? Lazy
    self.unwrap == o.unwrap
  else
    self.unwrap == o
  end
end

#equals?(o) ⇒ Boolean

Returns:

  • (Boolean)


187
188
189
# File 'lib/monads/lazy.rb', line 187

def equals? o
  eql? o
end

#finalizeObject

Complete any pending operations and return the result, wrapped in a Final. Eg: Lazy(10).bind { |i| i * i }.finalize # ==> Final[100]



151
152
153
# File 'lib/monads/lazy.rb', line 151

def finalize
  Final[unwrap]
end

#to_sObject



174
175
176
# File 'lib/monads/lazy.rb', line 174

def to_s
  "Pending[#{ @fun }]"
end

#unwrapObject

Complete any pending operations and return the result, unwrapped. Eg: Lazy(10).bind { |i| i * i }.unwrap # ==> 100



157
158
159
# File 'lib/monads/lazy.rb', line 157

def unwrap
  @fun.call
end