memoize (is this a fix for overloading?)

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Jan 4 13:25:20 PST 2011


On 1/4/11 2:57 PM, %u wrote:
> Hi all,
>
> How does this work, with respect to overloading?
>
> auto memo(alias Fn, TParams...)(TParams args) if (isCallable!(Fn))
> {
>      static typeof(Func(args))[Tuple!(TParams)] cache;
>      auto key = tuple(args);
>      return key in cache ? cache[key] : (cache[key] = Func(args));
> }
>
> uint fib(uint n)
> { return n>  1 ? memo!(fib)(n - 1) + memo!(fib)(n - 2) : n; }
> ulong fib(ulong n)
> { return n>  1 ? memo!(fib)(n - 1) + memo!(fib)(n - 2) : n; }
>
> void main() { memoize(&fib); std.stdio.writefln("%d", fib(50)); }
>
>
> It seems like it's fixed, right?

There's still the risk of keeping multiple hashes. Consider:

ulong fun(ulong n) { ... }
alias memoize!fun mfun;

mfun(5); // creates hash ulong[int]
mfun(5u); // creates hash ulong[uint]
mfun('5'); // creates hash ulong[char]


Andrei


More information about the Digitalmars-d mailing list