Am 22.08.2010 21:45, schrieb bearophile:
(...)
import std.stdio: writeln;
import std.typecons: Tuple, tuple;
import std.traits: ReturnType, ParameterTypeTuple;

struct Memoize(alias F) {
     ReturnType!F opCall(ParameterTypeTuple!F args) {
         alias ReturnType!F ResultType;
         static ResultType[Tuple!(ParameterTypeTuple!F)] cache;
         auto ptr = tuple(args) in cache;
         if (ptr == null) {
             auto result = F(args);
             cache[tuple(args)] = result;
             return result;
         } else {
             return *ptr;
         }
     }
}

pure int fib(int n) {
     if (n<  2)
         return n;
     return fib(n - 1) + fib(n - 2);
}

void main() {
     pure int delegate(int n) cfib_impl;
     Memoize!cfib_impl cfib;

     cfib_impl = (int n) {
         if (n<  2)
             return n;
         return cfib(n - 1) + cfib(n - 2);
     };

     enum int N = 40;
     writeln("fib(", N, ") = ", fib(N));
     writeln("cfib(", N, ") = ", cfib(N));
}

Bye,
bearophile
I see; I should use template magic. Oh, and I used Tuple the wrong way beacuse I've never used it before.
Thanks

Mafi

Reply via email to