misc/memoize.scm -rw-r--r-- 793 bytes View raw Log this file
0a51cb856ebb — Linus Bj√∂rnstam Moved the data structures to a different repo 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
;; A slow memoization macro. Uses hash tables.
;; depends on guile's behaviour of letting one
;; painlessly use lists as hash table keys.

(define-module (memoize)
  #:export (lambda/memo define/memo))

(define-syntax define/memo
  (syntax-rules ()
    [(define/memo (name arg args ...)
       body body* ...)
     (define name
       (lambda/memo (arg args ...)
         body body* ...))]))

(define-syntax lambda/memo
  (syntax-rules ()
    [(lambda/memo (arg args ...) body body* ...)
     (let ([memory (make-hash-table)])
       (lambda (arg args ...)
         (let ([m (hash-ref memory (list arg args ...) #f)])
           (if m
               m
               (let ([res (let () body body* ...)])
                 (hash-set! memory (list arg args ...) res)
                 res)))))]))