Writing an auto-memoizer in Scheme. Help with macro and a wrapper.

Posted by kunjaan on Stack Overflow See other posts from Stack Overflow or by kunjaan
Published on 2009-06-30T22:28:38Z Indexed on 2010/06/08 21:12 UTC
Read the original article Hit count: 222

I am facing a couple of problems while writing an auto-memoizer in Scheme.

I have a working memoizer function, which creats a hash table and checks if the value is already computed. If it has been computed before then it returns the value else it calls the function.

(define (memoizer fun)
  (let ((a-table (make-hash)))
    (?(n)
      (define false-if-fail (?() #f))
      (let ((return-val (hash-ref a-table n false-if-fail)))
        (if return-val
            return-val
            (begin
              (hash-set! a-table n (fun n))
              (hash-ref a-table n)))))))

Now I want to create a memoize-wrapper function like this:

(define (memoize-wrapper function)
  (set! function (memoizer function)))

And hopefully create a macro called def-memo which defines the function with the memoize-wrapper. eg. the macro could expand to (memoizer (define function-name arguments body ...) or something like that.

So that I should be able to do :

(def-memo (factorial n)
  (cond
    ((= n 1) 1)
    (else (* n (factorial (- n 1))))))

which should create a memoized version of the factorial instead of the normal slow one.

My problem is that the

  1. The memoize-wrapper is not working properly, it doesnt call the memoized function but the original function.
  2. I have no idea how to write a define inside of the macro. How do I make sure that I can get variable lenght arguments and variable length body? How do I then define the function and wrap it around with the memoizer?

Thanks a lot.

© Stack Overflow or respective owner

Related posts about functional-programming

Related posts about macros