aboutsummaryrefslogtreecommitdiff
path: root/gn/cache/memoize.scm
diff options
context:
space:
mode:
Diffstat (limited to 'gn/cache/memoize.scm')
-rw-r--r--gn/cache/memoize.scm33
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)))))))