[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] Memoizing a procedure

From: F. Wittenberger
Subject: Re: [Chicken-users] Memoizing a procedure
Date: Mon, 29 Nov 2010 13:53:07 +0100

Hi Hugo,

Am Sonntag, den 28.11.2010, 17:27 +0100 schrieb Peter Bex:
> On Sun, Nov 28, 2010 at 12:53:53PM -0300, Hugo Arregui wrote:
> > Hi guys,
> Hi Hugo!
> > I wrote a small code to add procedure memoization, most for learning
> > purposes (attached).
> > I'm glad to ear your suggestions.

Since it's for learning purposes, you might want to consider whether or
not your memoized procedures will ever be used in a threaded


> (define (make-memoized proc)
>   (let ((memo (make-hash-table))
>         (missing (list 'missing)))
>     (lambda args
>       (let ((result (hash-table-ref/default memo args missing)))
>         (when (eq? result missing)
>           (set! result (apply proc args))
>           (hash-table-set! memo args result))
>         result))))

would become something like:

(define (make-memoized proc)
  (let ((memo (make-hash-table))
        (missing (list 'missing)))
    (lambda args
      (let ((result (hash-table-ref memo args
                                    (lambda ()
                                      (let ((x (cons missing (make-mutex))))
                                        (hash-table-set! memo args x)
        (when (and (pair? result) (eq? (car result) missing))
          (let ((mux (cdr result)))
            (mutex-lock! mux)
            (when (and (pair? result) (eq? (car result) missing))
              (set! result (apply proc args))
              (hash-table-set! memo args result))
            (mutex-unlock! mux)))

Note, however that this will not work, if your memoized procedure
terminates by exception!

reply via email to

[Prev in Thread] Current Thread [Next in Thread]