lazy evaluation

Daniel Keep daniel.keep.lists at gmail.com
Mon Jun 4 03:22:37 PDT 2007


I'm not sure how you'd account for lazy arguments, but it should be
possible to abstract memorisation of function results.  Warning:
untested and likely non-compiling code follows, but it should at least
be in the right ballpark :)

	--Daniel

 --

template memoImpl(alias fn)
{
    alias typeof(&fn) fnT;
    private ReturnType!(fnT)[Tuple!(ParameterTypeTuple!(fnT))] results;

    ReturnType!(fnT) memo(ParameterTypeTuple!(fnT) args)
    {
        auto targs = tuple(args);
        if( !(targs in results) )
            results[targs] = fn(args);
        return results[targs];
    }
}

template memo(alias fn)
{
    alias memoImpl!(fn).memo memo;
}

class Foo
{
    int _foo(char[] bar)
    {
        // ... some complex calculation ...
    }

    alias memo!(_foo) foo;
}



More information about the Digitalmars-d mailing list