Run define from message passing

Viewed 51
(define (memoize message f)
  (define (dispatch message)
    (cond 
     ((eq? message 'm) k)
     ((eq? message 'um) 20)))

  (define (k) 
    (let ((table (make-table)))
      (lambda (x)
        (let ((previously-computed-result (lookup x table)))
          (or previously-computed-result
              (let ((result (f x)))
                (insert! x result table)
                result)
              )))))
  f)

(set! fib(memoize 'm fib))

My idea is that I am sending m, as the message, then the ((eq? message 'm) k) will check true so define k will run and change the fib because of set!, but the code does not work as I expect it to work, could someone help me out please

1 Answers

You need to call dispatch and return the result. You're just returning the same function you were called with.

And in dispatch you need to call k, not just return it, since it returns the closure that has the lookup table.

(define (memoize message f)
  (define (dispatch message)
    (cond 
     ((eq? message 'm) (k))
     ((eq? message 'um) 20)))

  (define (k) 
    (let ((table (make-table)))
      (lambda (x)
        (let ((previously-computed-result (lookup x table)))
          (or previously-computed-result
              (let ((result (f x)))
                (insert! x result table)
                result)
              )))))
  (dispatch message))
Related