Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 832
unj2 Avatar asked Jun 30 '09 22:06

unj2


1 Answers

this is what i use in PLT scheme:

#lang scheme

(define (memo f)
  (define mh (make-hash))
  (lambda p
    (hash-ref mh p (lambda ()
                     (hash-set! mh p (apply f p))
                     (hash-ref mh p)))))

(define-syntax-rule (defmemo (id . p) . body)
  (define id (memo (lambda p . body))))

(provide defmemo)
like image 116
Javier Avatar answered Oct 04 '22 05:10

Javier