lazy evaluation

Denton Cockburn diboss at hotmail.com
Fri Jun 1 20:01:44 PDT 2007


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:
>> Pierre Habouzit wrote:
>> >  lazy types are supported through the Lazy module, and forcing the
>> >evaluation of a lazy type is done through Lazy.force expr rather than
>> >expr() like in D. Though, like you can see, once forced, the lazy
>> >expression sees its value memoized.
>> >  I'm wondering:
>> >  * why lazy types in D don't work like that for lazy parameters,
>> >    because it's really what makes sense and is the most predictible
>> >    behaviour ;
>> >  * also why it's not a generic type attribute either and only used as a
>> >    function parameter. Not knowing the implementation gory details, I
>> >    don't know if it makes sense at all anyway.
>> 
>> 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;
}



More information about the Digitalmars-d mailing list