lazy evaluation

Pierre Habouzit pierre.habouzit at m4x.org
Mon Jun 4 01:00:30 PDT 2007


On Sat, Jun 02, 2007 at 03:01:44AM +0000, Denton Cockburn wrote:
> On Fri, 01 Jun 2007 20:47:45 +0000, Pierre Habouzit wrote:
> > On Fri, Jun 01, 2007 at 03:26:34PM -0500, Tyler Knott wrote:
> >> In D lazy parameters are implemented as anonymous delegates.  This means 
> >> that
> >> 
> >> void baz(lazy int i)
> >> {
> >> 	writefln("baz %d", i);
> >> }
> >> 
> >> is transformed to
> >> 
> >> void baz(int delegate() i)
> >> {
> >> 	writefln("baz %d", i());
> >> }
> >> 
> >> where the delegate i references is whatever code you used for that 
> >> argument.  So in your example each time i evaluated you call an anonymous 
> >> function that calls foo() and returns its return value.  If you want the 
> >> value to stay consistent between evaluations of i use a temporary 
> >> variable to store the result of it or make it non-lazy.
> > 
> >   hmm okay, so lazy is just syntaxic sugar then. That's a pity, because
> > I believe it's restrictive, but well... too bad :)
> >
> 
> well, if you don't want it to re-evaluate on each instance, why not just...
> 
> int main()
> {
>     int f = foo();
>     bar(f);
>     return 0;
> }

  My example is oversimplistic. Though if you are e.g. writing (not so
random example) an interpreter of some language, and for one or another
reason you don't really want to go in the hassle of bytecode or
intermediary language. One way to speed things up is to evaluate your
parse tree lazily. Of course, that could be explicitely coded, but it's
way easier if the language gives you that gratis.

  As a general rule, in many complex applications, you often have
somehow complex operations (parse, compilation, hashing, whatever) that
you do "just in case", because it's easier to suppose this operation has
been done unconditionnaly, rather than using everywhere you need the
parse/compilation/hash/... available things like:

  if (foo->did_i_parsed_it())
      foo->parse();
  use_parse_of_foo(foo->parseresult);

  Because one day, you'll forget about it. If you have the lazy
expressions I'm talking about, then instead of doing the real parse in
your program, you just need to write the lazy expression that once
evaluated will compute the parse/compilation/whatever.

  Then you use your foo->parseresult member as a lazy expression, that
will be evaluated iff your application really needed it.

  Though, maybe this don't need to be done with the D lazy construct
though, but I didn't came with a satisfying implementation yet. (I mean
one that has a light enough syntax for the lazy expression use).

-- 
·O·  Pierre Habouzit
··O                                                madcoder at debian.org
OOO                                                http://www.madism.org



More information about the Digitalmars-d mailing list