CS212 Exams
Spring 1997 - Prelim
2

Memoization


In this problem you are to write a procedure memoize which takes as input a procedure f of one argument and returns a procedure that produces the same value as f on any input but which only computes f once for any particular value. That is, the first call to the resulting procedure with a given argument computes the value of f on that argument and then stores and returns the value. Subsequent calls with that same argument simply look up and return the stored value.

For instance, consider the following procedure defined using memoize,

(define test 
  (memoize (lambda ((x <number>))
             (echo 'computing)
             (* x x))))

The following calls then result in the output shown in the following transcript:

==>(test 5)
computing
25

==>(text 4)
computing
16

==>(test 5)
25

Write the procedure memoize.




Solution

Return to CS 212 Prelim 2 - Spring 1997