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
Thanks a lot.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With