Paste number 46421: memo

Index of paste annotations: 2 | 1

Paste number 46421: memo
Pasted by: cin
When:2 years, 5 months ago
Share:Tweet this! | http://paste.lisp.org/+ZTH
Channel:None
Paste contents:
Raw Source | XML | Display As
(define memo (make-hash-table 'equal))

(define (memoize force-update func . params)
  (define (update-value func params)
    (let ((ret-value (apply func params)))
      (hash-table-put! memo (apply list (cons func params)) ret-value)
      ret-value))
  (if force-update
      (update-value func params)
      (let ((memo-get (hash-table-get memo (apply list (cons func params)) #:void)))
        (if (eq? #:void memo-get)
            (update-value func params)
            memo-get))))


;; usage

(memoize #f <func> <arg1> <argn> ...) ;; returns cached version

(memoize #t <func> <arg1> <argn> ...) ;; refreshes the cache

Annotations for this paste:

Annotation number 2: better?
Pasted by: Cin
When:2 years, 5 months ago
Share:Tweet this! | http://paste.lisp.org/+ZTH/2
Paste contents:
Raw Source | Display As
(define (memoize force-update func . params)
  (define (update-value func params)
    (let ((ret-value (apply func params)))
      (hash-table-put! memo (apply list (cons func params)) ret-value)
      ret-value))
  (if force-update
      (update-value func params)
      (hash-table-get memo
		      (apply list (cons func params))
		      (lambda () (update-value func params)))))

Annotation number 1: better
Pasted by: Cin
When:2 years, 5 months ago
Share:Tweet this! | http://paste.lisp.org/+ZTH/1
Paste contents:
Raw Source | Display As
(define (memoize force-update func . params)
  (define (update-value func params)
    (let ((ret-value (apply func params)))
      (hash-table-put! memo (apply list (cons func params)) ret-value)
      ret-value))
  (if force-update
      (update-value func params)
      (with-handlers ((void (lambda (exn) (update-value func params))))
		     (hash-table-get memo (apply list (cons func params))))))

Colorize as:
Show Line Numbers
Index of paste annotations: 2 | 1

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.