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

落花浮王杯 提交于 2019-12-10 14:50:00

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/1066414/writing-an-auto-memoizer-in-scheme-help-with-macro-and-a-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!