blah = promise { 3 }
p blah.methods.include? "+" # => false, failed to force
force( blah )
p blah.methods.include? "+" # => true
...and:
foo = promise { 3 }
begin
p [foo] # TypeError: can't convert Lazy::Thunk into Integer
rescue TypeError => e
puts e
end
force( foo )
p [foo] # => nil
Same problem in both cases, basically.
Oh, and if you try these in irb, remember that you will get different
results because irb's attempt to display the result value will force the
promise.
-mental
···
On Fri, 2005-11-04 at 16:42 +0900, Pit Capitain wrote:
Hi mental,
do you have some unit tests or an example where implicit forcing isn't
working as you'd like?
MenTaLguY schrieb:
> ...
> Same problem in both cases, basically.
Here's another implementation that doesn't have these problems:
module Lazy #:nodoc: all
class Thunk
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
def initialize( &computation ) @computation = computation
end
def method_missing( *args, &block )
( @result ||= @computation.call( self ) ).send( *args, &block )
end
end
end
Ah, that clarifies things. This is essentially a pass-thru Functor with
a cached result. (Why is 'self' being passed to the computation
though?) While not quite the same as the implict lambda's I suggested,
it is interesting just how similar they are.
This whole Functor paradigm, including things like #every, #enum_for, #as (was #superfunc), etc. and now this --all are various simple
decorators of a special form where the heart of code is some sort of
transfomation in method_missing. Insteresting stuff. It would be even
more interesting to see if this could somehow be embodied in core so to
operate more efficiently (and perhaps a syntax variation on the
methods?) --this techinque may have potential for roles and namespace
selectors too.