Skip to content

Instantly share code, notes, and snippets.

@baioc
Last active February 19, 2021 09:59
Show Gist options
  • Save baioc/ec050bd470f55d7e4a537e576f3b8add to your computer and use it in GitHub Desktop.
Save baioc/ec050bd470f55d7e4a537e576f3b8add to your computer and use it in GitHub Desktop.
Automatic Memoization with Closures
;; make a function that caches its past results
(define (memoize proc)
(let ((cache (make-table)))
(define (delegate . args)
(let ((hit (lookup cache args)))
(or hit ; or miss
(let ((result (apply proc args)))
(insert! cache args result)
result))))
delegate))
;; GUILE specific
(define make-table make-hash-table)
(define lookup hash-ref)
(define insert! hash-set!)
;; usage example
(define memo-fib
(memoize (lambda (n)
(cond ((= n 0) 0)
((= n 1) 1)
(else (+ (memo-fib (- n 1))
(memo-fib (- n 2))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment