[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Chicken-users] Memoizing a procedure
From: |
Hugo Arregui |
Subject: |
Re: [Chicken-users] Memoizing a procedure |
Date: |
Sun, 28 Nov 2010 23:42:20 -0300 |
Thanks for your comments Peter!, they are very interesting.
> It looks good to me. It only works for simple procedures though,
> not for procedures with optional arguments or keyword arguments.
> Keyword args can be in any order, and an optional argument can be
> identical to a missing argument when it has the value of the default.
I didn't know about keyword arguments in scheme. It's SRFI-88 stuff?
>And not for procedures returning zero or multiple values.
You right.
> A small optimization would be not to check the hash table first and
> then perform another lookup. You could perform one lookup and have
> that immediately check whether the value is stored in the hash table:
>
> (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))))
Collateral question: it's there a difference between define vars into
make-memoized directly or inside a let?
> I don't think the advice egg would add a lot. You could use it like
> this:
>
> ---------------------------------------------------------------------------
> (use srfi-69 advice)
> (define-syntax mdefine (syntax-rules ()
> ((mdefine (proc v ...) body ...)
> (begin (define (proc v ...) body ...)
> (memoize proc)))))
>
> (define (memoize proc)
> (let ((memo (make-hash-table))
> (missing (list 'missing)))
> (advise 'around proc
> (lambda (inner args)
> (let ((result (hash-table-ref/default memo args missing)))
> (when (eq? result missing)
> (set! result (apply inner args))
> (hash-table-set! memo args result))
> result))
> 'memoized)))
>
> (define (dememoize proc)
> (unadvise proc 'memoized))
Cool, this is a pretty good example for around mode.
Thanks again Peter!