Chapter 3, Modularity, Objects, and State
Exercise 3.27
This is little tricky to understand. Lets break it down piece by piece:
memoizeis straightforward.- It takes a procedure ‘f’ and returns another procedure.
- The returned procedure is bound to the environment created by the call to
memoize, where a table was created. - Thus returned procedure has access to this table.
- This returned procedure takes an argument
xand first checks, if there value available in the table for the key x. If yes, it returns the value. - If not, it calls the procedure
fwithxas an argument and saves the result in the table as well as returns the result. Note thatfis also available to this returned procedure by the environment. - Thats it!
memo-fibis nothing but the procedure returned bymemoize. Andfis the lambda function that we passed tomemo-fiband which contains the code for fibonacci.- It may seems a bit tricky that
f(the lamda function we passed) is itself callingmemo-fib. - But this is nothing but indirect recursion! ‘memo-fib’ –calls–> f(the lambda function passed to memoize) –calls–> ‘memo-fib’.
- As we can see the recursion calls are for lower values of
nand we have a base case at n = 0 and 1. - The important thing to note that all these recursive calls of
memo-fibare executed in the environment where parent environment points to the environment in whichmemo-fibwas created. - Well, technically
mem-fibis created in global environment. When speaking ofmemo-fib, I am referring to the procedure which the variablememo-fibpoints to. Thus even if themem-fibvariable belongs to global-env the procedure it points to is created/bound to a different environment. - Thats it!
- It may seems a bit tricky that
Now th last past - Would the scheme still work if we had simply defined memo-fib to be (memoize fib)?
No.
Here things will not work because fib itself calls fib recursively thus no table lookups happen.