Kevin Robert Stravers
This package provides macros for defining memoized functions. A memoized function stores its results in a hasheq table. Multiple arguments invoke nested hasheq tables.
It also provides manners to finalize or destroy memoized values.
syntax
( memoize (param...+)body...+)
syntax
( define/memoize (nameparam...+)body...+)
> (fib100)573147844013817084101
Accessing the cache is done by calling the function without any arguments. So it can be reset by doing the following:
One can also simply remove the desired entries inside (fib), and then use set-box! to store it back to the function. Finalization occurs if a finalizer is specified and the GC happens to collect your removed value.
For multiple arguments the hash becomes nested with respect to the parameters:
> (f123)6
> (f)'#&#hasheq((1. #hasheq((2. #hasheq((3. 6))))))
syntax
( memoize-zero body...+)
syntax
( define/memoize-zero namebody...+)
> (example)"This runs once and only once"
'value
> (example)'value
Access to the zero version is granted by providing a dummy argument. Here we use 'get-cache for clarity.
> (example'get-cache)'#&#<void>
'#&#t
> (example)"This runs once and only once"
'value
> (example'get-cache)'#&value
'#&#f
Two values are returned; the cache itself (inside a box ), as well as the first-time? flag, also in a box . This flag indicates whether or not the cache should computed.
Sometimes we wish to write partially memoized functions, for instance, when we compute a side-effect and we want to cache some important result before doing the side-effect. A good use-case is OpenGL, where we may need to generate a texture or load a glProgram.
syntax
(live-param...)#:hashhsh#:finalizefinalizer(memoized-body...)(live-body...+))
syntax
(memoized-param...)(live-param...)#:hashhsh#:finalizefinalizer(memoized-body...)(live-body...+))
> (partial123)"Runs once for each unique x and y"
9
> (partial)'#&#hasheq((1. #hasheq((2. #<procedure:.../pkgs/memo/main.rkt:108:19>))))
> (partial124)12
> (partial003)"Runs once for each unique x and y"
0
> (partial)'#&#hasheq((0. #hasheq((0. #<procedure:.../pkgs/memo/main.rkt:108:19>)))(1. #hasheq((2. #<procedure:.../pkgs/memo/main.rkt:108:19>))))
> (partial000)0
> (f12)"Runs once for each unique x and y"
30
> (f)'#&#hasheq((1. #hasheq((2. #<procedure:.../pkgs/memo/main.rkt:80:19>))))
> (f12)30
str)> (memoize-with-hash1"A string")"A string"
"A string"
> (memoize-with-hash)'#&#hash((1. #hash(("A string". "A string"))))