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.
This commit is contained in:
commit
4df60ead93
172 files changed
+4403
No files matched your search
@@ -0,0 +1,32 @@
|
||||
;;; 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*))))))
|
||||
Reference in new issue
Block a user