[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Axiom-developer] Function cache in Axiom (Memoizing)

From: Tim Daly
Subject: [Axiom-developer] Function cache in Axiom (Memoizing)
Date: Wed, 18 Nov 2009 23:24:38 -0500
User-agent: Thunderbird (Windows/20090302)

Bertfried, Franz,

I have been giving some thought to your need for caching.
There is a technique in lisp called memoizing which basically
creates a new hash table in a closure and then defines a function
which closes over it and wraps the original function.

So when you call
(memoize originalfunction)
then you get back a new function to replace the original.
This new function first looks in the locally created cache
and returns what it finds. If it does not have a cached value
then it calls the original function, caches the result and
returns the result. Hash tables are local to the function so
there can be no collisions with values from other domains.

I know you're not common lisp readers but knowing what it does
should make this code obvious:

(defun memoize (fn)
 (let ((cache (make-hash-table :test #'equal)))    ;local hashtable
#'(lambda (&rest args) ;function to return (multiple-value-bind (val win) ;win is true if found (gethash args cache) ;is it in the cache? (if win val ;yes, return cache
             (setf (gethash args cache) (apply fn args))))))) ;no. do call

In my more clever moments it might be possible to create a new function
in the API domain called memoize that could be applied to other spad
functions. This isn't one of those moments, unfortunately.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]