diff options
author | Pjotr Prins | 2023-08-06 10:51:13 +0200 |
---|---|---|
committer | Pjotr Prins | 2023-08-06 10:51:13 +0200 |
commit | a00edcbc54026ea956ca41029474ff0e6a838616 (patch) | |
tree | be37fe002c23b59626391657a6c56e9665f4e0bd /gn/cache/memoize.scm | |
parent | dedcfeee0ce72539f0789923229c54b00f23605d (diff) | |
download | gn-guile-a00edcbc54026ea956ca41029474ff0e6a838616.tar.gz |
memoize: created separate module
Diffstat (limited to 'gn/cache/memoize.scm')
-rw-r--r-- | gn/cache/memoize.scm | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/gn/cache/memoize.scm b/gn/cache/memoize.scm new file mode 100644 index 0000000..e7ccc33 --- /dev/null +++ b/gn/cache/memoize.scm @@ -0,0 +1,33 @@ +;; Defines simple memoization functions. Currently it uses an alist - +;; we should change that to a hash. Also we want the cache to expire +;; after some time. memoize2 is now a separate function to deal +;; specifically with two return values. That is not ideal either. + +;; Basically lifted from +;; https://lispdreams.wordpress.com/2016/04/08/lisp-memoization-techniques/ + +(define-module (gn cache memoize) + #:export (memoize + memoize2)) + +(define (memoize f) + "Simple memoize just uses alists at this point and does not expire" + (let ((result-table '())) + (lambda (. args) + (let ((cache-value (assoc args (pk result-table)))) + (if (pk cache-value) + (cdr cache-value) + (let ((result (apply f args))) + (set! result-table + (alist-cons args result result-table)) result)))))) + +(define (memoize2 f) + "Simple memoize functions that returns values pair and uses alists at this point and does not expire" + (let ((result-table '())) + (lambda (. args) + (let ((c (assoc args (pk result-table)))) + (if (pk c) + (values (car (cdr c)) (car (cdr (cdr c)))) + (let-values (((r1 r2) (apply f args))) + (set! result-table + (alist-cons args (list r1 r2) result-table)) (values r1 r2))))))) |