From a00edcbc54026ea956ca41029474ff0e6a838616 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 6 Aug 2023 10:51:13 +0200 Subject: memoize: created separate module --- gn/cache/memoize.scm | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 gn/cache/memoize.scm (limited to 'gn') 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))))))) -- cgit v1.2.3