chicken-users
[Top][All Lists]
Advanced

[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 14:29:49 +0100

Am Montag, den 29.11.2010, 13:53 +0100 schrieb Jörg F. Wittenberger:
> 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,
> (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)
>                                       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)))
>         result))))
> 
> Note, however that this will not work, if your memoized procedure
> terminates by exception!

Note also, that hash tables in chicken are not thread safe, hence you'd
need some more locking anyway.  Left as an exercise.

Be warned however, that you don't want to grow that code too much.
"Recently" - that is I'm still kind of screwing with it - wrote some
code, which handles such cases, plus some optional features like
timeout's for the result being taken to be valid (which comes in handy,
when you want to memoize procedures, which return temporary valid values
(e.g., network connections), cache-cleanup's.  It can easily outgrow the
scope of an educational exercise.




reply via email to

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