Last active
February 19, 2021 09:59
-
-
Save baioc/ec050bd470f55d7e4a537e576f3b8add to your computer and use it in GitHub Desktop.
Automatic Memoization with Closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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