CS212 Exams
Spring 1997 - Prelim
2

Solution to Memoization

WARNING: You should seriously try to answer this question before looking at the solution -- it's just a good study skill. Also, some answers on this page may be more brief than you would want to put down in an actual exam. If you want any type of partial credit, you should write more than just the solution.


(define memoize
  (let ((memory empty))
    (lambda ((f <function>))
      (lambda (x)
        (let ((test (assq x memory)))
          (if test
            (tail test)
            (let ((z (f x)))
              (set! memory (cons (cons x z) memory))
              z)))))))
; notice that it returns the pair (x (f x)) instead of just (f x)
; this is so (f x)=> #f is distinguished from #f
; common errors include: using append to set! the memory, using global state

Question

Return to CS 212 Prelim 2 - Spring 1997