From: Michael Neumann Date: 2004-05-01T06:47:03+09:00 Subject: Re: Lazy evaluation On Sat, May 01, 2004 at 05:38:03AM +0900, Jean-Hugues ROBERT wrote: > At 03:45 01/05/2004 +0900, you wrote: > >Hi, > > > >I am currently hacking a Packrat parser just for fun. I need to mix > >values (like numbers, strings etc.) together with lazy values. I want to > >make processing these values as transparent as possible. > > [...] > >Any comments or suggestions? > > > >Regards, > > > > Michael > > Comments ? Not much. Besides the fact that we both need some kind of a > Reference class to inherit from. > > You to do: > class LazyValue < Reference > ... > > Me to do: > class LogicVariable < Reference > > In both cases we want automatic dereferencing of the object when its > value is required. Something like the Delegator class in delegate.rb is useful. I wrote my own lazy version: class Lazy self.methods.reject{|m| m =~ /^__(.*)__$/}.each {|m| eval "def #{m}(*args, &block) __getobj__.send(:'#{m}', *args, &block) end" } def initialize(*args, &block) raise "no block given" if block.nil? @args, @block = args, block end def __getobj__ if @block @value = @block.call(*@args) @block = @args = nil end return @value end def marshal_dump __getobj__ end def marshal_load(obj) @value = obj end def method_missing(id, *args, &block) __getobj__.send(id, *args, &block) end end And to replace all Lazy objects with their values, I can now use obj = Marshal.load(Marshal.dump(obj)). > As far as I know the least intrusive notation is to use the [] and []= > accessors that you can redefine. Be carefull with []=, the assigned > value is not under its control (use xx.[]= yy syntax instead). Hm, don't really understand that. > I expect soon to have the issue striking again while implementing > "Future". Kind of lazy evaluation. A "Future" is the result of a > method call that is not available yet, but you don't mind, until > you need it, then you block until it is available. That is a > useful concept for distributed computing. Hm, sounds a bit like Oz :-) or similar to promises in E-lang? Regards, Michael