Search code examples
d

Is it possible to use User Defined Attributes to get values at runtime?


What I really would like to do is cache/memoize certain function arguments and results. I understand in d there's User Defined Attributes, but it appears theres no way to get runtime values with it. Am I mistaken? Is there another similar design pattern I could use here to get similar results?

@memoize("expensiveCalc")
int expensiveCalc(string foo){
    ///bar
}

So memoize is actually a function that gets called. However, it utilizes the value of my arguments to quickly hash parameters and call the actual function.
Similar to this:

def memoize(iden, time = 0, stale=False, timeout=30):
    def memoize_fn(fn):

        def new_fn(*a, **kw):

            #if the keyword param _update == True, the cache will be
            #overwritten no matter what
            update = kw.pop('_update', False)
            key = make_key(iden, *a, **kw)
            res = None if update else memoizecache.get(key)
            if res is None:
                        # okay now go and actually calculate it
                    res = fn(*a, **kw)
                    memoizecache.set(key, res, time=time)



            return res

        new_fn.memoized_fn = fn
        return new_fn
    return memoize_fn

Solution

  • For what you're trying to do, you'll want a wrapper template rather than a UDA. Phobos actually has one for memoization: http://dlang.org/phobos/std_functional.html#memoize

    UDAs in D are used to add information to a function (or other symbol, types and variables too), but they don't actually modify it. The pattern is to have some other code read all the names with reflection, look at the UDAs, and generate the new code that way. If you want to get runtime values from a UDA, you'd write a function that reads it with compile time reflection, then returns the value. Calling that function at runtime gives the UDA there. If you'd like to know more, I can write it up, but I think std.functional.memoize will do what you want here. Remember, UDAs in D add information, they don't change or create code.