www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 20099] New: Memoize should handle lambdas

https://issues.dlang.org/show_bug.cgi?id=20099

          Issue ID: 20099
           Summary: Memoize should handle lambdas
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: phobos
          Assignee: nobody puremagic.com
          Reporter: simen.kjaras gmail.com

Currently, std.functional.memoize uses std.traits.ReturnType and
std.traits.Parameters to get the return type and parameters of the memoized
function. This fails for stuff like memoize!(a => a.field). Suggested new
implementation:

template memoize(alias fun) {
    auto memoize(Args...)(Args args) if (is(typeof(fun(args)))) {
        import std.typecons : Tuple;

        static if (__traits(isTemplate, fun)) {
            import std.traits : isDelegate;
            static assert(!isDelegate!(fun!Args), fun.stringof~" is a delegate,
and thus has context memoize can't access.");
        }

        static typeof(fun(args))[Tuple!Args] memo;
        auto t = Tuple!Args(args);
        if (auto p = t in memo)
            return *p;
        return memo[t] = fun(args);
    }
}

--
Aug 02 2019