memoize

bearophile bearophileHUGS at lycos.com
Tue Jan 4 02:07:07 PST 2011


Andrei:

> I just added a higher-order function memoize to std.functional which I 
> think is pretty cool. See the docs here:

I am not sure it's a good idea to put inside the D docs a link to the Google PDF visualizer.

I suggest to remove the fact() example, because given the other fib() example, it adds nothing. Or if you want to keep it, you may differentiate it, showing something different, like putting the alias outside (and renaming the function).


>The maxSize parameter is a cutoff for the cache size. If upon a miss the length of the hash table is found to be maxSize, the table is simply cleared.<

Two alternatives I'd like better:
1) The simpler alternative: when maxSize!=uint.max the associative array values are linked in a singly linked list. When there's a cache miss and aa.length > maxSize then the last item of the linked list is removed (there is a pointer to the last item that gets updated to the penultimate).

2) A bit more complex: when maxSize!=uint.max the associative array values are linked in a singly linked list. If the requested key is present, its value moves to the head of the doubly linked list. If it's not present, it's added at the head of the linked list. If aa.length > maxSize then the last item of the linked list is removed (a simple LRU implementation). A Python version:
http://code.activestate.com/recipes/498110-memoize-decorator-with-o1-length-limited-lru-cache/

Of course I have written a memoize myself:
http://code.activestate.com/recipes/466320-another-memoize/

Python has function decorators, so there's no need to change the name of memoized functions nor to change the function contents.

Bye,
bearophile


More information about the Digitalmars-d mailing list