;;; DYNAMIC 3: A MEMOIZING CLOSURE ;;; ;;; Closures plus hash tables: remember what you computed. The ;;; counter below watches how many times the slow function really ;;; runs; a memoized second call must not run it again. (defparameter *fib-calls* 0) (defun slow-fib (n) (incf *fib-calls*) (if (< n 2) n (+ (slow-fib (- n 1)) (slow-fib (- n 2))))) ;; TODO: A closure over a hash table: when N is already in the ;;; table, return the stored answer; otherwise compute it with ;;; SLOW-FIB, store it, and return it. (defun make-memo-fib () (let ((table (make-hash-table))) (lambda (n) (slow-fib n)))) ;;; ------------------------------------------------------------------ ;;; Checks. Read them - they tell you what to aim for - but leave ;;; them unchanged. ;;; ------------------------------------------------------------------ (check (let ((fib (make-memo-fib))) (setf *fib-calls* 0) (and (eql 55 (funcall fib 10)) (let ((after-first *fib-calls*)) (and (eql 55 (funcall fib 10)) (eql after-first *fib-calls*))))))