Files
lisplings/exercises/18_dynamic/dyn3.lisp
T
venomade 4df60ead93 Lisplings: Rustlings-style exercises for Common Lisp
70 exercises in 20 chapters, from first s-expressions to restarts,
macros, CLOS, and a tiny Lisp interpreter. Each exercise ships
broken with a solved twin and a hint. Includes a watch-mode runner,
a plain-CL check harness, a nix flake, and verification tooling.
All plain SBCL, no dependencies.
2026-11-22 03:30:19 +00:00

33 lines
1.1 KiB
Common Lisp

;;; 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*))))))