Wave 4: add sequences/vectors/files chapters, 23 exercises, quiz3, finish ceremony, PCL table

This commit is contained in:
venomade committed 2026-11-22 11:15:35 +00:00
1 parent 77843402fa
commit 4675bd1106
76 files changed
+2505 -14

No files matched your search

+48 -2
View File
@@ -115,7 +115,7 @@ live in the same file you edit, which is the Lispy way.
## The course
70 exercises in 20 chapters, from first forms to restarts, macros,
105 exercises in 23 chapters, from first forms to restarts, macros,
and a tiny Lisp interpreter:
```text
@@ -123,13 +123,59 @@ and a tiny Lisp interpreter:
04_conditionals 05_predicates 06_lists 07_recursion
08_functional 09_strings 10_loops 11_numbers
12_structs 13_hash_tables 14_packages 15_clos
16_conditions 17_macros 18_dynamic quizzes
16_conditions 17_macros 18_dynamic 19_sequences
20_vectors 21_files quizzes
```
Each chapter directory has a README with a two-line summary of the
ideas, and every exercise has a hint (`h`) and a solved twin under
`solutions/`.
## Chapter to book mapping
Two references will carry you from here. [Practical Common Lisp]
(http://www.gigamonkeys.com/book/) ("PCL") is the book this course
runs parallel to; the [Common Lisp HyperSpec]
(https://www.lispworks.com/documentation/HyperSpec/Front/) ("CLHS")
is the language's complete reference. Where each chapter points:
| Lisplings chapter | PCL | CLHS |
| --- | --- | --- |
| 00_intro | ch. 1-2 (Introduction; A Tour of the REPL) | n/a |
| 01_sexps | ch. 4 (Syntax and Semantics) | §2-3 (character syntax, evaluation) |
| 02_functions | ch. 5 (Functions) | §3 (lambda, function) |
| 03_variables | ch. 6 (Variables) | §3 (let, let*, defvar), §5 (setf) |
| 04_conditionals | ch. 7 (Macros: Standard Control Constructs) | §5 (data and control flow) |
| 05_predicates | n/a (equality bits live in ch. 4 and ch. 10) | §4 (types), §5 (eq, eql, equal, equalp) |
| 06_lists | ch. 11-12 (Collections; List Processing) | §14 (conses) |
| 07_recursion | ch. 12-13 (lists, trees) | §14 (conses) |
| 08_functional | ch. 5, ch. 11-12 (function values; mapcar and friends) | §17 (mapcar), §5 (funcall, apply) |
| 09_strings | ch. 10 (Numbers, Characters, and Strings); ch. 18 (A Few FORMAT Recipes) | §16 (strings), §22 (format) |
| 10_loops | ch. 7 (dolist, dotimes); LOOP for Black Belts | §6 (iteration) |
| 11_numbers | ch. 10 (Numbers, Characters, and Strings) | §12 (numbers) |
| 12_structs | n/a (PCL goes straight to objects, ch. 16-17) | §8 (structures) |
| 13_hash_tables | ch. 11 (Collections) | §18 (hash tables) |
| 14_packages | n/a (no dedicated PCL chapter) | §11 (packages) |
| 15_clos | ch. 16-17 (Object Reorientation) | §7 (objects) |
| 16_conditions | ch. 19 (Beyond Exception Handling: Conditions and Restarts) | §9 (conditions) |
| 17_macros | ch. 7-8 (Standard Control Constructs; Defining Your Own) | §3 (defmacro, macroexpand) |
| 18_dynamic | ch. 6 (closures, special variables) | §3 (dynamic binding), §5 (catch, throw) |
| 19_sequences | ch. 11 (Collections: sequence functions) | §17 (sequences) |
| 20_vectors | ch. 11 (vectors; strings are vectors, ch. 10) | §15 (arrays), §16 (strings) |
| 21_files | ch. 14-15 (Files and File I/O; A Portable Pathnames Library) | §19-21 (filenames, files, streams) |
| quizzes | quiz3: ch. 11, ch. 13; quiz1: ch. 3, ch. 13; quiz2: ch. 4 | n/a |
## The finish line
When the last check of the last exercise passes, lisplings prints
its closing message: the lambda from the top of this README, now
yours, plus where to go next - which Practical Common Lisp
chapters follow the course, how Quicklisp and ASDF fit in, and a
reminder that (describe) and (apropos) answer questions right in
the REPL. The text lives in `info.sexp` under `:final`; make it
yours. Want to keep going? Add the exercise you wish had been
there - the recipe is in "Hacking on lisplings" below.
## Hacking on lisplings
Lisplings itself is a few hundred lines of SBCL with no dependencies:
+44
View File
@@ -0,0 +1,44 @@
;;; S-EXPRESSIONS 4: READER SHORTHAND
;;;
;;; The reader turns characters into objects before evaluation ever
;;; sees them. A few two-character shortcuts do real work:
;;;
;;; 'x (quote x) - the last exercise's trick
;;; #'f (function f) - the function itself
;;; #(...) a vector, read as one literal object
;;; #x10 hexadecimal 16
;;;
;;; The checks below ask with FUNCTIONP (T for a function object)
;;; and VECTORP (T for a vector); chapter 05 collects such
;;; questions. The DEFSTRUCT declares the POINT record - chapter
;;; 12 explains it, and here it only gives the reader a type to
;;; build.
(defstruct point x y)
;; TODO: The function that adds numbers - the function itself, not
;; its name.
(defun the-adder ()
'+)
;; TODO: The counting numbers 1, 2, 3 as ONE vector literal.
(defun counting ()
'(1 2 3))
;; TODO: The point at X 1, Y 2, read straight from text.
(defun origin ()
(list :x 1 :y 2))
;; TODO: The web color deadbeef - 3735928559 - in hex digits.
(defun magic-web-number ()
3735928558)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (functionp (the-adder)))
(check (vectorp (counting)))
(check (point-p (origin)))
(check-equal 3735928559 (magic-web-number))
+28
View File
@@ -0,0 +1,28 @@
;;; FUNCTIONS 5: PRODUCING VALUES
;;;
;;; FUNCTIONS 4 let values ride along by passing FLOOR through. This
;;; time you MAKE them: (values a b) returns two values at once.
;;;
;;; MOD gives a remainder: (mod 265 100) => 65. FLOOR gives the
;;; whole part: (floor 265 100) => 2.
;;;
;;; The checks gather the values with MULTIPLE-VALUE-LIST again.
;; TODO: CENTS as two values: whole DOLLARS and leftover cents.
(defun split-money (cents)
(list (floor cents 100) (mod cents 100)))
;; TODO: N as two values: half of it, and double it. (/ 7 2) is the
;; exact rational 7/2 - fine.
(defun half-and-double (n)
(* n 2))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(2 65) (multiple-value-list (split-money 265)))
(check-equal '(0 5) (multiple-value-list (split-money 5)))
(check-equal '(3 12) (multiple-value-list (half-and-double 6)))
(check-equal '(7/2 14) (multiple-value-list (half-and-double 7)))
+41
View File
@@ -0,0 +1,41 @@
;;; CONDITIONALS 5: CASE AND ECASE
;;;
;;; COND's tidy cousin for dispatching on one value:
;;;
;;; (case fruit
;;; ((apple banana) "cheap")
;;; ((mango) "pricey")
;;; (t "unknown"))
;;;
;;; The keys are compared with EQL, and a (t ...) clause catches
;;; everything else. Leave the fallback out and CASE quietly answers
;;; NIL. ECASE is CASE without the safety net: no matching key, and
;;; it signals a TYPE-ERROR instead.
;; TODO: Fruits are priced: apples and bananas "cheap", mangoes and
;; durians "pricey", anything else "unknown".
(defun rate-fruit (fruit)
(case fruit
((apple banana) "cheap")
((mango) "pricey")))
;; TODO: :open means "come in", :closed means "knock first" - and
;; any other state is not a state at all: let ECASE complain.
(defun door-state (state)
(case state
(:open "come in")
(:closed "knock first")))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "cheap" (rate-fruit 'apple))
(check-equal "cheap" (rate-fruit 'banana))
(check-equal "pricey" (rate-fruit 'mango))
(check-equal "pricey" (rate-fruit 'durian))
(check-equal "unknown" (rate-fruit 'kiwi))
(check-equal "come in" (door-state :open))
(check-equal "knock first" (door-state :closed))
(check-error (door-state :ajar) 'type-error)
+35
View File
@@ -0,0 +1,35 @@
;;; PREDICATES 4: EQL AND EQUALP
;;;
;;; The ladder has two rungs exercise 2 left unclimbed:
;;;
;;; EQL same object, or the same number or character - same type
;;; too: (eql 1 1.0) is NIL.
;;; EQUALP the generous one: numbers by value - (equalp 1 1.0) is
;;; T - characters ignoring case.
;;;
;;; Fix each definition with the comparison its comment names.
;; TODO: EQL - the very same number, 1 and 1.0 disagree.
(defun same-exact-p (a b)
(= a b))
;; TODO: EQUALP - the same amount, 1 and 1.0 agree.
(defun same-amount-p (a b)
(eql a b))
;; TODO: EQUALP - the same letter, case ignored.
(defun same-twin-p (a b)
(equal a b))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (same-exact-p 7 7))
(check (not (same-exact-p 1 1.0)))
(check (not (same-exact-p 1 2)))
(check (same-amount-p 1 1.0))
(check (not (same-amount-p 1 2)))
(check (same-twin-p #\a #\A))
(check (not (same-twin-p #\a #\b)))
+29
View File
@@ -0,0 +1,29 @@
;;; LISTS 6: DESTRUCTURING-BIND
;;;
;;; LET binds one name; DESTRUCTURING-BIND binds a whole lambda
;;; list of names at once, pulling them out of a list:
;;;
;;; (destructuring-bind (w h d) dims
;;; (* w h d))
;;;
;;; The dotted template (x . rest) splits the head from the tail,
;;; like CAR and CDR in one go.
;; TODO: The volume of a box given as (width height depth).
(defun dimensions (dims)
(destructuring-bind (w h d) dims
(* w d)))
;; TODO: XS as two values: the first element, and the rest.
(defun first-and-rest (xs)
(list (car xs) (cdr xs)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 60 (dimensions '(3 4 5)))
(check-equal 0 (dimensions '(0 10 2)))
(check-equal '(1 (2 3)) (multiple-value-list (first-and-rest '(1 2 3))))
(check-equal '(a ()) (multiple-value-list (first-and-rest '(a))))
+24
View File
@@ -0,0 +1,24 @@
;;; RECURSION 5: MUTUAL RECURSION
;;;
;;; Two functions can take turns: each calls the other on (1- n) -
;;; one less - until zero settles the question. LABELS defines
;;; local functions that can see and call each other:
;;;
;;; (labels ((up (k) ... (down (1- k)))
;;; (down (k) ... (up (1- k))))
;;; (up n))
;; TODO: T when the whole number N is even, NIL when odd. Take
;; turns subtracting one, inside LABELS, until zero answers.
(defun my-evenp (n)
(zerop n))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (my-evenp 0))
(check (my-evenp 4))
(check (not (my-evenp 7)))
(check (not (my-evenp 1)))
+26
View File
@@ -0,0 +1,26 @@
;;; STRINGS 5: NUMBERS IN FORMAT
;;;
;;; ~a prints any value plainly. ~d and ~f print numbers with more
;;; care, and both take modifiers: a COLON on ~d groups the digits,
;;; (format nil "~:d" 1234567) => "1,234,567"
;;; and a number after a comma on ~f fixes the decimals,
;;; (format nil "~,2f" pi) => "3.14"
;; TODO: N widgets, grouped for humans: "1,234,567 widgets".
(defun price-tag (n)
(format nil "~d widgets" n))
;; TODO: LABEL is about N, with exactly two decimals:
;; "pi is about 3.14".
(defun fixed (label n)
(format nil "~a is about ~a" label n))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "1,234,567 widgets" (price-tag 1234567))
(check-equal "7 widgets" (price-tag 7))
(check-equal "pi is about 3.14" (fixed "pi" pi))
(check-equal "e is about 2.72" (fixed "e" 2.718281828))
+32
View File
@@ -0,0 +1,32 @@
;;; STRINGS 6: FORMAT PICKS AND CASE
;;;
;;; FORMAT has its own conditional, for choosing between texts:
;;;
;;; (format nil "~[tick~;tock~]" 1) => "tock"
;;;
;;; The argument is a number: 0 picks the first branch, 1 the
;;; second. And ~( ... ~) folds everything between them to lower
;;; case - STRING-DOWNCASE in FORMAT's clothing:
;;;
;;; (format nil "~(~a~)" "GRACE") => "grace"
;; TODO: "tick" on an even N, "tock" on an odd one - let FORMAT
;; choose.
(defun tick-tock (n)
(format nil "tick"))
;; TODO: The title S, downcased.
(defun quiet-title (s)
(format nil "~a" s))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "tick" (tick-tock 0))
(check-equal "tock" (tick-tock 1))
(check-equal "tick" (tick-tock 2))
(check-equal "tock" (tick-tock 5))
(check-equal "grace" (quiet-title "GRACE"))
(check-equal "ada lovelace" (quiet-title "ADA LOVELACE"))
+38
View File
@@ -0,0 +1,38 @@
;;; STRINGS 7: NEWLINES AND COLUMNS
;;;
;;; ~% ALWAYS breaks the line. ~& breaks one only when you are not
;;; at the start of a line already - fresh line, not newline - so a
;;; brand-new string gets nothing:
;;;
;;; (format nil "~&~a" "hi") => "hi"
;;;
;;; ~v takes the field width from the arguments, and @ pads on the
;;; left - right-justified:
;;;
;;; (format nil "~v@a" 6 "ada") => " ada"
;; TODO: S on a fresh line: nothing before it when the line is
;; already new.
(defun add-line (s)
(format nil "~%~a" s))
;; TODO: NAME right-justified in a field WIDTH wide.
(defun right-column (name width)
(format nil "~va" width name))
;; TODO: A receipt row: ITEM in an 8-wide column, PRICE right-
;; justified in 4.
(defun receipt (item price)
(format nil "~a ~a" item price))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "hi" (add-line "hi"))
(check-equal "parrot" (add-line "parrot"))
(check-equal " ada" (right-column "ada" 6))
(check-equal "hi" (right-column "hi" 2))
(check-equal "tea 2" (receipt "tea" 2))
(check-equal "coffee 3" (receipt "coffee" 3))
+32
View File
@@ -0,0 +1,32 @@
;;; LOOPS 4: LOOP'S OTHER CLAUSES
;;;
;;; FOR X = 1 THEN (* X 2) keeps a running value: 1 the first time
;;; round, the THEN expression on every step after. WITH binds a
;;; variable once, for the whole loop. UNTIL stops the loop when its
;;; test turns true; WHILE is the same test upside down.
;;;
;;; (loop repeat 4 for x = 1 then (* x 2) collect x) => (1 2 4 8)
;; TODO: The first N doublings of 1: (1 2 4 8) for N = 4.
(defun doublings (n)
(loop for i from 1 to n
collect i))
;; TODO: The prices in XS, until adding the next one would push the
;; running total to CAP or past it.
(defun cart-until-cap (xs cap)
(loop for p in xs
until (>= p cap)
collect p))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(1 2 4 8) (doublings 4))
(check-equal '(1) (doublings 1))
(check-equal '() (doublings 0))
(check-equal '(3 5) (cart-until-cap '(3 5 2 8) 10))
(check-equal '() (cart-until-cap '(20 1) 10))
(check-equal '(1 2) (cart-until-cap '(1 2 3 4) 6))
+38
View File
@@ -0,0 +1,38 @@
;;; LOOPS 5: DO AND DO*
;;;
;;; DO is LOOP's ancestor, spelled out:
;;;
;;; (do ((i 1 (1+ i)) (total 0 (+ total i)))
;;; ((> i n) total))
;;;
;;; Each variable gets an initializer and a STEP. The step
;;; expressions all see the OLD values - like LET. DO* steps one at
;;; a time - like LET* - so a later step can use an earlier
;;; variable's NEW value. That difference is exactly what the
;;; factorial below needs.
;; TODO: The sum 1 + 2 + ... + N, the DO way.
(defun triangle-do (n)
(do ((i 1 (1+ i))
(total 0 total))
((> i n) total)))
;; TODO: N factorial: 1 * 2 * ... * N, with B seeing A's new value
;; - DO*, not DO.
(defun factorial-of (n)
(do ((a 1 (1+ a))
(b 1 (* b a)))
((>= a n) b)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 6 (triangle-do 3))
(check-equal 55 (triangle-do 10))
(check-equal 0 (triangle-do 0))
(check-equal 1 (factorial-of 0))
(check-equal 1 (factorial-of 1))
(check-equal 6 (factorial-of 3))
(check-equal 24 (factorial-of 4))
+45
View File
@@ -0,0 +1,45 @@
;;; LOOPS 6: COUNT, MAXIMIZE, LOOP-FINISH
;;;
;;; LOOP accumulates more than lists: COUNT tallies the iterations
;;; whose test is true, MAXIMIZE tracks the biggest value seen (0
;;; for an empty run, so WIDEST below answers NIL itself).
;;;
;;; LOOP-FINISH leaves the iterations early, gently: the FINALLY
;;; clause still runs, so (finally (return total)) hands the value
;;; back either way. NAMED gives a loop a name to leave by:
;;; (loop named block-name ... (return-from block-name value))
;; TODO: How many odd numbers XS holds.
(defun count-odds (xs)
(loop for x in xs
count x))
;; TODO: The largest number in XS - NIL when XS is empty.
(defun widest (xs)
(loop for x in xs
sum x))
;; TODO: The total you can reach without going over LIMIT: add each
;; X, but stop the moment the next one would push the total past
;; LIMIT.
(defun first-sum-over (xs limit)
(loop with total = 0
for x in xs
do (setf total (+ total x))
finally (return total)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 3 (count-odds '(1 2 3 4 5)))
(check-equal 0 (count-odds '(2 4)))
(check-equal 0 (count-odds '()))
(check-equal 9 (widest '(3 9 2)))
(check-equal 4 (widest '(4)))
(check-equal nil (widest '()))
(check-equal 5 (first-sum-over '(2 3 4) 8))
(check-equal 9 (first-sum-over '(2 3 4) 100))
(check-equal 0 (first-sum-over '(9 9) 8))
(check-equal 0 (first-sum-over '() 5))
+42
View File
@@ -0,0 +1,42 @@
;;; NUMBERS 4: TYPE DECLARATIONS
;;;
;;; DECLARE is a promise to the compiler - no check, just knowledge
;;; it may use for faster code:
;;;
;;; (defun twice (n)
;;; (declare (type integer n))
;;; (* 2 n))
;;;
;;; DECLAIM makes a global promise; THE wraps one expression:
;;; (the integer n). CHECK-TYPE is the live gate. It checks, and
;;; lies are TYPE-ERRORs:
;;;
;;; (check-type n integer)
;;;
;;; Compound types work too: (integer 0 100) is a whole number
;;; from 0 to 100.
;; TODO: Double N - but only when N really is an integer; other
;; values are type-errors.
(defun counted-double (n)
(check-type n string)
(* 2 n))
;; TODO: 100 minus N, for a whole N from 0 to 100 - anything
;; outside is a type-error.
(defun shrink (n)
(check-type n integer)
(- 100 n))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 10 (counted-double 5))
(check-equal 0 (counted-double 0))
(check-error (counted-double "five") 'type-error)
(check-equal 60 (shrink 40))
(check-equal 100 (shrink 0))
(check-error (shrink 200) 'type-error)
(check-error (shrink -3) 'type-error)
+44
View File
@@ -0,0 +1,44 @@
;;; HASH TABLES 4: MAPHASH
;;;
;;; MAPHASH walks every key and value pair, handing each to a
;;; function of two arguments - the key first:
;;;
;;; (maphash (lambda (key value) ...) table)
;;;
;;; The order of the walk is not promised, so build answers that do
;;; not care about order.
(defparameter *stock*
(let ((table (make-hash-table)))
(setf (gethash 'tea table) 2
(gethash 'coffee table) 3
(gethash 'cocoa table) 4)
table))
;; TODO: The total number of items in stock.
(defun stock-total ()
(let ((total 0))
(maphash (lambda (key value)
(incf total key))
*stock*)
total))
;; TODO: The keys of TABLE, as a list.
(defun keys-of (table)
(let ((keys '()))
(maphash (lambda (key value)
(push value keys))
table)
keys))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 9 (stock-total))
(check (let ((keys (keys-of *stock*)))
(and (= 3 (length keys))
(member 'tea keys)
(member 'coffee keys)
(member 'cocoa keys))))
+46
View File
@@ -0,0 +1,46 @@
;;; PACKAGES 4: FIND-SYMBOL AND INTERN
;;;
;;; FIND-SYMBOL answers "does this package keep a symbol with this
;;; spelling?" - two values: the symbol, and how it is kept -
;;; :EXTERNAL for exported, :INTERNAL for the rest, NIL and NIL
;;; when there is no such name:
;;;
;;; (find-symbol "CAR" 'common-lisp) => CAR, :EXTERNAL
;;;
;;; With no package argument it searches *PACKAGE*, the current
;;; one - what IN-PACKAGE last set. INTERN finds the symbol or
;;; MAKES it; SYMBOL-NAME is a symbol's spelling as a string.
(defpackage #:attic
(:use #:common-lisp)
(:export #:heirloom))
(in-package #:attic)
(defun heirloom ()
'grandmas-ring)
(in-package #:common-lisp-user)
;; TODO: The symbol ATTIC keeps under the string NAME, with how it
;; is kept as a second value - (NIL NIL) when there is none.
(defun attic-lookup (name)
(find-symbol name))
;; TODO: The ATTIC symbol called NAME - interning a fresh one when
;; the attic does not keep that name yet.
(defun attic-intern (name)
(find-symbol name 'attic))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(attic:heirloom :external)
(multiple-value-list (attic-lookup "HEIRLOOM")))
(check-equal '(nil nil)
(multiple-value-list (attic-lookup "GHOST")))
(check (attic-intern "SPARE-KEY"))
(check-equal "SPARE-KEY" (symbol-name (attic-intern "SPARE-KEY")))
(check (eq 'attic:heirloom (attic-intern "HEIRLOOM")))
+51
View File
@@ -0,0 +1,51 @@
;;; PACKAGES 5: INTERNALS, NICKNAMES, SHADOWING
;;;
;;; A single colon reaches only EXPORTED symbols. The double colon
;;; shop::secret-sale reaches the internal ones too. :NICKNAMES
;;; gives a package extra names to call it by. And :SHADOW keeps a
;;; name a package USEs from colliding with your own - without it,
;;; defining FILL below would quietly redefine COMMON-LISP's FILL
;;; for everyone.
(defpackage #:shop
(:use #:common-lisp)
(:nicknames #:store)
(:export #:price))
(in-package #:shop)
(defun price ()
5)
(defun secret-sale ()
2)
(in-package #:common-lisp-user)
;; TODO: The secret sale price SHOP keeps for regulars only.
(defun best-deal ()
(shop:price))
;; TODO: The defpackage below is missing its (:shadow #:fill).
;; Add it, or DEFUN FILL under POST-OFFICE redefines COMMON-LISP's
;; FILL for everyone.
(defpackage #:post-office
(:use #:common-lisp))
(in-package #:post-office)
(defun fill (box)
(list 'stuffed box))
(in-package #:common-lisp-user)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 5 (store:price))
(check-equal 2 (best-deal))
(check-equal (list 0 0 0) (fill (list 1 2 3) 0))
(check-equal '(post-office::stuffed crate)
(funcall (find-symbol "FILL" '#:post-office) 'crate))
+37
View File
@@ -0,0 +1,37 @@
;;; CLOS 5: WITH-SLOTS AND WITH-ACCESSORS
;;;
;;; Slot access through POINT-X and POINT-Y works, but spells the
;;; name out every time. WITH-SLOTS reads the slots as plain
;;; variables:
;;;
;;; (with-slots (x y) p (list x y))
;;;
;;; WITH-ACCESSORS does the same through the accessor names, so
;;; SETF goes through the accessor too:
;;;
;;; (with-accessors ((x point-x)) p (setf x (1+ x)))
(defclass point ()
((x :initarg :x :accessor point-x)
(y :initarg :y :accessor point-y)))
;; TODO: The point P with both coordinates doubled - a NEW point.
(defun double-point (p)
(make-instance 'point :x (* 2 (point-x p)) :y (point-y p)))
;; TODO: P with its X stepped up by one - the SAME point, changed.
(defun shift-x (p)
(setf (point-x p) (+ 2 (point-x p)))
p)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (let ((q (double-point (make-instance 'point :x 3 :y 4))))
(and (eql 6 (point-x q)) (eql 8 (point-y q)))))
(check (let ((p (shift-x (make-instance 'point :x 1))))
(eql 2 (point-x p))))
(check (let ((p (shift-x (make-instance 'point :x 10))))
(eql 11 (point-x p))))
+39
View File
@@ -0,0 +1,39 @@
;;; CLOS 6: CALL-NEXT-METHOD AND NEXT-METHOD-P
;;;
;;; A method can stand on the one above it: CALL-NEXT-METHOD runs
;;; the next most specific method and hands its answer back, so you
;;; can build on it. When there is no next method, CALL-NEXT-METHOD
;;; itself errors - NEXT-METHOD-P asks first.
;;;
;;; (defmethod speak ((d dog))
;;; (concatenate 'string (call-next-method) " Woof!"))
(defclass animal () ())
(defclass dog (animal) ())
(defclass cat (animal) ())
(defgeneric announce (a))
(defmethod announce ((a animal))
"I am an animal.")
(defgeneric purr (a))
;; TODO: A DOG announces what an animal announces, then adds
;; " Woof!".
(defmethod announce ((d dog))
"Woof!")
;; TODO: CAT purrs: if a method above you exists, use its answer;
;; otherwise say "Prrr".
(defmethod purr ((c cat))
(call-next-method))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "I am an animal. Woof!" (announce (make-instance 'dog)))
(check-equal "I am an animal." (announce (make-instance 'animal)))
(check-equal "Prrr" (purr (make-instance 'cat)))
+36
View File
@@ -0,0 +1,36 @@
;;; CLOS 7: PRINT-OBJECT AND DEFAULT-INITARGS
;;;
;;; DEFSTRUCT (chapter 12) writes the constructor, the readers and
;;; the predicate for you. DEFCLASS spells them out by hand - and
;;; buys methods, inheritance, and defaults:
;;;
;;; :INITFORM fills one slot when nothing else does.
;;; :DEFAULT-INITARGS feeds an :INITARG its default, so
;;; MAKE-INSTANCE can still override it.
;;;
;;; PRINT-OBJECT is the method the printer calls: define it, and
;;; PRINC shows your objects your way. PRINT-UNREADABLE-OBJECT
;;; builds the #<...> frame around your text.
(defstruct candy filling size)
;; TODO: POINT starts at the origin unless you say otherwise.
(defclass point ()
((x :initarg :x :accessor point-x)
(y :initarg :y :accessor point-y)))
;; TODO: A point prints as #<POINT x=3 y=4>.
(defmethod print-object ((p point) stream)
(format stream "point"))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 'swirl (candy-filling (make-candy :filling 'swirl)))
(check-equal 0 (point-x (make-instance 'point)))
(check-equal 7 (point-x (make-instance 'point :x 7)))
(check-equal "#<POINT x=3 y=4>"
(with-output-to-string (s)
(princ (make-instance 'point :x 3 :y 4) s)))
+53
View File
@@ -0,0 +1,53 @@
;;; CONDITIONS 5: REPORTS, WARN, SIGNAL
;;;
;;; DEFINE-CONDITION (exercise 3) names a condition class; the
;;; :REPORT option gives it the text humans see - and PRINC of the
;;; condition prints that text.
;;;
;;; ERROR unwinds to the debugger. WARN reports and CARRIES ON - it
;;; signals a WARNING, catchable like anything else. SIGNAL is the
;;; bare mechanism: handlers see it, nobody else is bothered.
(define-condition low-battery (condition) ())
;; TODO: A condition of your own, EMPTY-CART - a subclass of ERROR
;; with :report "The cart is empty - nothing to check out." - and
;; CHECKOUT signals it when ITEMS is NIL.
(define-condition empty-cart (error)
())
(defun checkout (items)
(when (null items)
(error 'empty-cart))
(list 'order items))
;; TODO: BATTERY-CHECK warns "battery ~a%!" when PERCENT is under
;; 20 - and returns (list 'battery percent) either way.
(defun battery-check (percent)
(error "battery ~a%!" percent)
(list 'battery percent))
;; TODO: CHECK-BATTERY signals LOW-BATTERY when PERCENT is at or
;; under 10 - a plain condition, not an error - then returns
;; (list 'battery percent).
(defun check-battery (percent)
(error "low battery")
(list 'battery percent))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(order (milk)) (checkout '(milk)))
(check-error (checkout '()) 'empty-cart)
(check-equal "The cart is empty - nothing to check out."
(handler-case (checkout '())
(empty-cart (c) (format nil "~a" c))))
(check-equal '(battery 15) (battery-check 15))
(check-equal '(battery 90) (battery-check 90))
(check-equal :noticed (handler-case (warn "battery low")
(warning () :noticed)))
(check-equal :swapped (handler-case (check-battery 5)
(low-battery () :swapped)))
(check-equal '(battery 20) (check-battery 20))
+36
View File
@@ -0,0 +1,36 @@
;;; CONDITIONS 6: RESTARTS WITH ARGUMENTS, IGNORE-ERRORS
;;;
;;; Exercise 4's restart carried no luggage. USE-VALUE takes an
;;; argument - a replacement the handling code chooses - and
;;; STORE-VALUE is its cousin for storing one and trying again.
;;; INVOKE-RESTART passes it over:
;;;
;;; (handler-bind ((parse-error
;;; (lambda (c) (invoke-restart 'use-value 42))))
;;; (parse-count "abc"))
;;;
;;; IGNORE-ERRORS wraps a form in cotton wool: anything it signals
;;; turns into NIL, and the condition rides along as a second
;;; value.
;; TODO: Parse TEXT as an integer - but offer a USE-VALUE restart
;; that answers with whatever value the caller hands over.
(defun parse-count (text)
(parse-integer text))
;; TODO: The integer in TEXT, or NIL when TEXT does not parse.
(defun maybe-age (text)
(parse-integer text))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 42 (handler-bind ((parse-error (lambda (c)
(declare (ignore c))
(invoke-restart 'use-value 42))))
(parse-count "abc")))
(check-equal 7 (parse-count "7"))
(check-equal 42 (maybe-age "42"))
(check-equal nil (maybe-age "abc"))
+26
View File
@@ -0,0 +1,26 @@
;;; MACROS 5: READER MACROS, A TASTER
;;;
;;; The # you know from #' and #(...) is a dispatch character: the
;;; character after it picks a reader function, and SET-DISPATCH-
;;; MACRO-CHARACTER installs one. The function takes (STREAM
;;; SUB-CHAR NUM-ARG) and returns the object the text becomes -
;;; the reader never evaluates, it only reads.
;;;
;;; (set-dispatch-macro-character #\# #\? #'reader)
;; TODO: Make #? read the NEXT form and hand it back wrapped in
;; (maybe ...): #?red should read as (maybe red). MAYBE-READER
;; below needs the fix; the registration line is already right.
(defun maybe-reader (stream sub-char num-arg)
(declare (ignore sub-char num-arg))
(read stream))
(set-dispatch-macro-character #\# #\? #'maybe-reader)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(maybe red) '#?red)
(check-equal '(maybe (1 2)) '#?(1 2))
+35
View File
@@ -0,0 +1,35 @@
;;; DYNAMIC 4: DEFVAR VS DEFPARAMETER
;;;
;;; Both define a special variable. The difference shows when their
;;; form runs AGAIN - a reload, say:
;;;
;;; DEFPARAMETER rebinds: the new value wins.
;;; DEFVAR only fills an EMPTY variable: what is there stays.
;;;
;;; So DEFVAR suits state the code fills in over time; DEFPARAMETER
;;; suits a constant you might retune. The file below runs both
;;; forms twice, the way a reload would.
(defvar *cache* 10)
(defparameter *config* 10)
;; The program grows the cache and retunes the config by hand:
(setf *cache* 99)
(setf *config* 99)
;; Re-evaluating the file, as a reload would:
(defvar *cache* 10)
(defparameter *config* 10)
;; TODO: The pair of values you see NOW.
(defun current-values ()
(list 10 10))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(99 10) (current-values))
(check-equal 99 *cache*)
(check-equal 10 *config*)
+7
View File
@@ -0,0 +1,7 @@
# 19_sequences
The generic sequence toolbox: FIND, REMOVE, SORT, SEARCH, MERGE.
Lists and vectors answer to the same functions, guided by :test
and :key. One set of names counts, filters, and rearranges either,
and EVERY and SOME ask questions of the whole.
+37
View File
@@ -0,0 +1,37 @@
;;; SEQUENCES 1: FIND, POSITION, COUNT
;;;
;;; A sequence is anything you can walk element by element: a list,
;;; a vector, a string. One toolbox serves them all.
;;; (find 2 '(1 2 3)) => 2 the element itself, or NIL
;;; (position 2 #(1 2 3)) => 1 where it sits, or NIL
;;; (count 'a '(a b a)) => 2 how many match
;;; :test decides what counts as a match. The default, EQL, treats
;;; 1 and 1.0 as different numbers; #'= does not.
;; TODO: The index where X sits in XS, or NIL.
(defun index-of (x xs)
(find x xs))
;; TODO: How many times X occurs in XS.
(defun occurrences (x xs)
(position x xs))
;; TODO: The first element of XS numerically equal to X, so that
;;; 1.0 can find the integer 1.
(defun find-same (x xs)
(find x xs))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 1 (index-of 'b #(a b c)))
(check-equal 2 (index-of 3 '(1 2 3)))
(check-equal nil (index-of 9 '(1 2 3)))
(check-equal 3 (occurrences 'a #(a b a c a)))
(check-equal 2 (occurrences 'b '(a b a b a)))
(check-equal 0 (occurrences 5 '(1 2 3)))
(check-equal 1 (find-same 1.0 '(2 1 3)))
(check-equal 2 (find-same 2.0 '(1 2 3)))
(check-equal nil (find-same 9 '(1 2 3)))
+33
View File
@@ -0,0 +1,33 @@
;;; SEQUENCES 2: REMOVE, REMOVE-IF, SUBSTITUTE
;;;
;;; All three return a fresh sequence and leave their input alone.
;;; REMOVE drops the matches; REMOVE-IF drops everything its
;;; predicate accepts; SUBSTITUTE swaps every match for a new
;;; element, reading its arguments as NEW, OLD, then the sequence.
;;; (remove 'b '(a b c b)) => (A C)
;;; (remove-if #'minusp '(-1 0 2)) => (0 2)
;;; (substitute 'x 1 '(1 2 1)) => (X 2 X)
;; TODO: XS with every occurrence of X dropped.
(defun drop-them (x xs)
(remove xs x))
;; TODO: XS with every negative number removed.
(defun drop-negatives (xs)
(remove-if #'plusp xs))
;; TODO: XS with every occurrence of OLD replaced by NEW.
(defun swap-them (new old xs)
(substitute old new xs))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(a c) (drop-them 'b '(a b c b)))
(check-equal '(1 3) (drop-them 2 '(2 1 2 3 2)))
(check-equal '(1 0 2) (drop-negatives '(-1 1 0 -2 2)))
(check-equal '(3) (drop-negatives '(-5 -3 3)))
(check-equal '(x 2 x) (swap-them 'x 1 '(1 2 1)))
(check-equal '(a b a) (swap-them 'a 'z '(z b z)))
+38
View File
@@ -0,0 +1,38 @@
;;; SEQUENCES 3: SORT, :KEY, REVERSE
;;;
;;; SORT arranges a sequence by a comparison function:
;;; (sort (list 3 1 2) #'<) => (1 2 3)
;;; SORT is allowed to rearrange the very sequence you hand it, so
;;; pass it a fresh one - the checks below all build with LIST.
;;; :key picks out the part to compare:
;;; (sort pairs #'< :key #'cdr) sorts by each pair's price
;;; REVERSE returns a backwards copy, and its input stays as it
;;; was: (reverse '(1 2 3)) => (3 2 1)
;; TODO: XS from smallest to largest.
(defun ascending (xs)
(sort xs #'>))
;; TODO: ALIST, a list of (item . price) pairs, sorted cheapest
;;; first.
(defun by-price (alist)
(sort alist #'< :key #'car))
;; TODO: Each word of XS reversed, with the words still in order.
(defun back-words (xs)
(reverse xs))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(1 2 3) (ascending (list 3 1 2)))
(check-equal '(-1 0 4) (ascending (list 4 0 -1)))
(check-equal '(3 2 1) (reverse (list 1 2 3)))
(check-equal '((tea . 1) (cola . 2))
(by-price (list (cons 'cola 2) (cons 'tea 1))))
(check-equal '((b . 1) (c . 2) (a . 7))
(by-price (list (cons 'a 7) (cons 'b 1) (cons 'c 2))))
(check-equal '("tac" "esaelp") (back-words '("cat" "please")))
(check-equal '("bba" "aa") (back-words '("abb" "aa")))
+44
View File
@@ -0,0 +1,44 @@
;;; SEQUENCES 4: EVERY, SOME, SEARCH, MERGE
;;;
;;; EVERY and SOME ask a question of a whole sequence. EVERY wants
;;; the predicate true of each element - the empty list qualifies.
;;; SOME settles for one:
;;; (every #'plusp '(1 2)) => T, (every #'plusp '()) => T
;;; (some #'minusp '(1 -2)) => T
;;; SEARCH hunts for a whole subsequence, not one element, and
;;; returns where it starts, or NIL:
;;; (search '(b c) '(a b c d)) => 1
;;; MERGE interleaves two sequences that are already in order, by
;;; the same kind of comparison SORT takes. Like SORT it may reuse
;;; its arguments:
;;; (merge 'list (list 1 3) (list 2 4) #'<) => (1 2 3 4)
;; TODO: T when every element of XS satisfies F, NIL otherwise.
(defun all-fit (f xs)
(some f xs))
;; TODO: The index where NEEDLE starts inside HAY, or NIL.
(defun needle-at (needle hay)
(find needle hay))
;; TODO: The elements of A and B together, in ascending order. A
;;; and B arrive already sorted.
(defun weave (a b)
(append a b))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal t (all-fit #'plusp '(1 2 3)))
(check-equal nil (all-fit #'plusp '(-1 2 3)))
(check-equal t (all-fit #'plusp '()))
(check (some #'minusp '(1 -2 3)))
(check-equal 1 (needle-at '(b c) '(a b c d)))
(check-equal 2 (needle-at '(2 3) '(1 5 2 3)))
(check-equal 1 (needle-at "ana" "banana"))
(check-equal nil (needle-at '(9) '(1 2 3)))
(check-equal '(1 2 3 4) (weave (list 1 3) (list 2 4)))
(check-equal '(0 1 4 9) (weave (list 4) (list 0 1 9)))
(check-equal '(2 3) (weave (list 2 3) (list)))
+7
View File
@@ -0,0 +1,7 @@
# 20_vectors
MAKE-ARRAY, AREF, fill pointers, and strings as vectors.
A vector is an array with a single index. MAKE-ARRAY builds one,
AREF reads and writes its slots, and a fill pointer marks how far
it is filled. A string is a vector of characters.
+42
View File
@@ -0,0 +1,42 @@
;;; VECTORS 1: MAKE-ARRAY, AREF, AND #(...)
;;;
;;; A vector is a one-dimensional array: a row of slots numbered
;;; from 0. Lists and vectors are both sequences.
;;; (make-array 3) => #(NIL NIL NIL)
;;; (make-array 3 :initial-element 0) => #(0 0 0)
;;; (vector 1 2 3) => #(1 2 3)
;;; #(1 2 3) is that same vector, written literally
;;; (aref #(a b c) 1) => B
;;; (setf (aref v 0) 'x) replaces slot 0
;;; (vectorp #(1 2)) => T, (vectorp '(1 2)) => NIL
;;; (length #(1 2 3)) => 3
;; TODO: The element stored in slot 1 of V.
(defun slot-one (v)
(aref v 0))
;; TODO: Put X in slot 0 of V and return V.
(defun replace-first (v x)
v)
;; TODO: A fresh vector with A, B, and C in its three slots.
(defun triple-vector (a b c)
(list a b c))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 'b (slot-one #(a b c)))
(check-equal 2 (slot-one #(1 2 3)))
(check-equal 'x
(aref (replace-first (make-array 2 :initial-element 'a) 'x)
0))
(check-equal 99
(aref (replace-first (make-array 3 :initial-element 0) 99)
0))
(check (vectorp (triple-vector 'a 'b 'c)))
(check (equalp #(p q r) (triple-vector 'p 'q 'r)))
(check-equal 'q (aref (triple-vector 'p 'q 'r) 1))
(check-equal 3 (length #(a b c)))
+48
View File
@@ -0,0 +1,48 @@
;;; VECTORS 2: FILL POINTERS AND GROWING VECTORS
;;;
;;; A vector can carry a fill pointer: the number of slots in use.
;;; VECTOR-PUSH stores a value past it and returns the slot index;
;;; on a full vector it returns NIL instead.
;;; (make-array 4 :fill-pointer 0) => empty, with room for 4
;;; (fill-pointer v) => slots in use
;;; (vector-push 'x v) => 0, the index it landed on
;;; VECTOR-PUSH-EXTEND grows the vector itself when it fills up, so
;;; the vector must be made :adjustable:
;;; (make-array 2 :fill-pointer 2 :adjustable t)
;; TODO: A vector with room for ROOM items, none in use yet.
(defun blank-row (room)
(make-array room))
;; TODO: Push X onto V three times, then return V.
(defun triple-push (v x)
v)
;; TODO: A fresh growable vector holding A and B.
(defun growable (a b)
(make-array 2 :initial-contents (list a b) :fill-pointer 2))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 0 (fill-pointer (blank-row 4)))
(check-equal 0 (vector-push 'z (blank-row 5)))
(check (let ((v (blank-row 3)))
(vector-push 'a v)
(equal 1 (fill-pointer v))))
(check-equal nil (vector-push 'x (make-array 2 :fill-pointer 2)))
(check-error (fill-pointer (make-array 3)))
(check-equal 3
(fill-pointer (triple-push (make-array 3 :fill-pointer 0)
'q)))
(check-equal 'q
(aref (triple-push (make-array 3 :fill-pointer 0) 'q)
2))
(check (let ((v (growable 'a 'b)))
(vector-push-extend 'c v)
(equal 'c (aref v 2))))
(check (let ((v (growable 1 2)))
(vector-push-extend 9 v)
(equal 9 (aref v 2))))
+41
View File
@@ -0,0 +1,41 @@
;;; VECTORS 3: STRINGS ARE VECTORS
;;;
;;; A string is a vector of characters, so the vector tools work on
;;; it unchanged. #\a is the character a.
;;; (aref "cat" 0) => #\c
;;; (length "cat") => 3
;;; (vectorp "cat") => T
;;; MAKE-ARRAY with :element-type 'character builds strings:
;;; (make-array 3 :element-type 'character :initial-element #\a)
;;; => "aaa"
;;; To change a string, work on your own copy: MAKE-ARRAY with
;;; :initial-contents duplicates an existing one.
;; TODO: The first character of the word W.
(defun first-letter (w)
(aref w 1))
;; TODO: W with its last character replaced by C. Leave the caller's
;;; string alone: build a copy first.
(defun retag (w c)
w)
;; TODO: A fresh string of N copies of the character C.
(defun letter-run (n c)
(make-array n))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (vectorp "cat"))
(check-equal #\c (first-letter "cat"))
(check-equal #\a (first-letter "apple"))
(check-equal "cab" (retag "cat" #\b))
(check-equal "suns" (retag "sung" #\s))
(check (let ((w "cat"))
(retag w #\b)
(equal "cat" w)))
(check-equal "aaa" (letter-run 3 #\a))
(check-equal "xx" (letter-run 2 #\x))
+6
View File
@@ -0,0 +1,6 @@
# 21_files
Files and streams: write, read back, parse.
WITH-OPEN-FILE closes for you; READ-LINE walks lines; PARSE-INTEGER
turns text into numbers.
+36
View File
@@ -0,0 +1,36 @@
;;; FILES 1: WITH-OPEN-FILE
;;;
;;; (with-open-file (stream path :direction :output) body) opens a
;;; file, runs the body, and closes the file afterwards - even when
;;; the body signals an error. :DIRECTION decides which way the
;;; stream flows: :output writes, and the default is :input.
;;;
;;; FORMAT's first argument can be a stream instead of NIL: the
;;; output lands in the file instead of a string.
;;;
;;; (format nil "...") => a string
;;; (format out "...") => into the file
;;;
;;; READ pulls ONE s-expression off a stream: the same reader that
;;; reads your code, reading the file's text instead.
(defparameter *note-file* "lisplings-note.txt")
;; TODO: Write the list (lisp is lovely) to *NOTE-FILE*, then
;; return T so the check below can see the save worked.
(defun save-note ()
(with-open-file (out *note-file*)
(format out "(lisp is lovely)~%")
t))
;; TODO: READ the list back out of *NOTE-FILE*.
(defun load-note ()
(read *note-file*))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-note))
(check-equal '(lisp is lovely) (load-note))
+41
View File
@@ -0,0 +1,41 @@
;;; FILES 2: READING LINES
;;;
;;; (read-line in) returns the next line as a string. At the end of
;;; the file it signals an error - unless you say what to hand back
;;; instead:
;;;
;;; (read-line in nil nil) => the next line, or NIL at the end
;;;
;;; NIL at the end is the base case the recursion chapter taught:
;;; read a line, cons it onto the rest.
;;;
;;; SAVE-POEM below is complete: the exercise writes the very file
;;; it reads, so the checks need nothing from outside.
(defparameter *poem-file* "lisplings-poem.txt")
(defun save-poem ()
(with-open-file (out *poem-file* :direction :output :if-exists :supersede)
(format out "(lisp is life)~%")
(format out "lambda forever~%")
(format out "close the parens~%"))
t)
(defun poem-lines ()
(with-open-file (in *poem-file*)
(poem-rest in)))
;; TODO: The lines still waiting in the stream IN, in order - NIL
;; once READ-LINE hands you NIL.
(defun poem-rest (in)
(read-line in))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-poem))
(check-equal '("(lisp is life)" "lambda forever" "close the parens")
(poem-lines))
(check-equal 3 (length (poem-lines)))
+36
View File
@@ -0,0 +1,36 @@
;;; FILES 3: PRINTING TO STREAMS
;;;
;;; PRIN1 prints readably - what the reader could read back, quotes
;;; included. PRINC prints for humans - no quotes. PRINT is PRIN1
;;; with a newline in front and a space behind. They all take the
;;; stream as their second argument.
;;;
;;; WITH-OUTPUT-TO-STRING makes a stream that collects into a
;;; string, so checks can watch printing without a file:
;;;
;;; (with-output-to-string (s)
;;; (princ "hi" s)) => "hi"
;; TODO: X twice: readable, one space, then plain.
(defun two-views (x)
(with-output-to-string (s)
(princ x s)
(princ " " s)
(princ x s)))
;; TODO: The label "name:" on its own line - PRINT starts the line
;; - then NAME after it, printed plainly.
(defun name-tag (name)
(with-output-to-string (s)
(princ "name:" s)
(princ name s)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "\"hi\" hi" (two-views "hi"))
(check-equal "7 7" (two-views 7))
(check-equal "
\"name:\" ada" (name-tag "ada"))
+46
View File
@@ -0,0 +1,46 @@
;;; FILES 4: NUMBERS FROM FILES
;;;
;;; A file full of text can be full of numbers wearing strings.
;;; PARSE-INTEGER takes one off:
;;;
;;; (parse-integer "42") => 42
;;;
;;; With :JUNK-ALLOWED T it reads the leading number and ignores
;;; the rest; without it, junk is a PARSE-ERROR. No number at all,
;;; and the junk-allowed answer is NIL.
;;;
;;; SAVE-COUNTS below is complete: the exercise writes the very
;;; file it reads.
(defparameter *count-file* "lisplings-counts.txt")
(defun save-counts ()
(with-open-file (out *count-file* :direction :output :if-exists :supersede)
(format out "10~%")
(format out "20~%")
(format out "5~%"))
t)
(defun sum-counts ()
(with-open-file (in *count-file*)
(sum-rest in)))
;; TODO: The lines of IN, each parsed into a number, added up.
(defun sum-rest (in)
(parse-integer (read-line in)))
;; TODO: The leading number in the string S, junk allowed - NIL
;; when S has no number at all.
(defun first-number (s)
(parse-integer s))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-counts))
(check-equal 35 (sum-counts))
(check-equal 12 (first-number "12 apples"))
(check-equal nil (first-number "no digits here"))
(check-error (parse-integer "12 apples") 'parse-error)
+3 -4
View File
@@ -1,7 +1,6 @@
# quizzes
Two capstones: a small program, then a tiny Lisp interpreter.
Quiz 1 assembles the basics into a working contact book. Quiz 2 is
the moment everything comes together: an evaluator for quoted
Three checkpoints now: quiz3 tallies everything up to conditions,
quiz1 assembles the basics into a working contact book, and quiz2
is the moment everything comes together: an evaluator for quoted
arithmetic s-expressions, written in the language it evaluates.
+62
View File
@@ -0,0 +1,62 @@
;;; QUIZ 3: THE LUNCH TALLY
;;;
;;; Everything from the chapters before macros in one working
;;; program: the waiters' pad is a list of orders, the kitchen
;;; counts them in a hash table, the prices live in an association
;;; list, and FORMAT writes the tally back out as a string.
;;;
;;; A price pair is (ITEM . COST), as in 06_lists: ASSOC finds the
;;; pair, its CDR is the cost.
(define-condition not-ordered (error)
((item :initarg :item :reader not-ordered-item))
(:documentation "Signaled when the kitchen is asked for an item nobody ordered."))
(defparameter *orders*
'(soup bread soup bread soup))
(defparameter *menu*
'((soup . 7) (bread . 3) (salad . 5)))
;; TODO: A fresh hash table mapping each ordered item to the number
;; of times it appears on the pad.
(defun tally-orders (orders)
(let ((table (make-hash-table)))
table))
;; TODO: How many of ITEM the kitchen must cook. Nobody ordered it
;;; at all? Signal not-ordered with :item ITEM.
(defun kitchen-count (table item)
0)
;; TODO: The price of ITEM from the menu alist, or 0 when the
;;; kitchen does not serve it.
(defun price-of (menu item)
0)
;; TODO: What the table owes: the price of every ordered item,
;;; added up.
(defun bill-total (orders menu)
0)
;; TODO: The items as one lowercase comma-separated line:
;;; "soup, bread, salad" for (SOUP BREAD SALAD).
(defun order-line (items)
"")
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (let ((table (tally-orders *orders*)))
(and (eql 3 (gethash 'soup table))
(eql 2 (gethash 'bread table))
(eql 2 (hash-table-count table)))))
(check-equal 3 (kitchen-count (tally-orders *orders*) 'soup))
(check-error (kitchen-count (tally-orders *orders*) 'pizza) 'not-ordered)
(check-equal 7 (price-of *menu* 'soup))
(check-equal 0 (price-of *menu* 'pizza))
(check-equal 27 (bill-total *orders* *menu*))
(check-equal "soup, bread, salad" (order-line '(soup bread salad)))
(check-equal 0 (hash-table-count (tally-orders '())))
+141 -8
View File
@@ -22,11 +22,39 @@ get started, here's how Lisplings works:
4. The REPL is your friend. Run `sbcl' in another terminal and try
forms interactively. That's the Lisp way!")
(:final "We hope you enjoyed Lisplings! You can now read and write
Common Lisp, and you know how to find out more: (describe 'foo),
(apropos \"foo\"), and the HyperSpec are your friends.
(:final "We hope you enjoyed Lisplings! You finished every
exercise, so the lambda is yours:
Found an issue, or want to add an exercise? Improvements welcome!")
/
/
/
/\\
/ \\
/ \\
Where to go from here:
1. Books. Practical Common Lisp (free at
http://www.gigamonkeys.com/book/) is the natural companion:
chapters 4-9 are the ground you just covered. Keep reading
ch. 10 (numbers, characters, strings), ch. 11 (collections),
ch. 12-13 (lists, plists, trees), ch. 14 (files and file I/O),
ch. 16-17 (objects), ch. 19 (conditions and restarts), and
LOOP for Black Belts. Its practical chapters then build whole
working programs, a spam filter among them.
2. Libraries. Quicklisp is how Common Lisp gets them: install it
once, and (ql:quickload :whatever) fetches any of thousands.
ASDF (asdf:defsystem) is how Lisp projects organize their
files into a system.
3. The REPL, always. (describe 'foo) prints what SBCL knows
about a name, (apropos \"foo\") lists every symbol containing
it, and the HyperSpec answers the rest.
4. Give back. Lisplings is plain Common Lisp and it wants your
exercises: write the broken file under exercises/<chapter>/,
the solved twin under solutions/, add a (:name ... :dir ...
:hint ...) entry to info.sexp, and run dev/verify.sh.
Good luck - and keep a REPL open. That's the Lisp way!")
(:exercises
((:name "intro1"
@@ -44,6 +72,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "sexps3"
:dir "01_sexps"
:hint "Quote stops evaluation: '(+ 1 2) is the LIST (+ 1 2). The single quote is reader shorthand for (quote x).")
(:name "sexps4"
:dir "01_sexps"
:hint "Reader shorthand: #'add is the function itself where '+ is only its name. #(1 2 3) reads a vector in one piece. #s(point :x 1 :y 2) reads a POINT structure. And #xdeadbeef spells 3735928559 in hex.")
(:name "functions1"
:dir "02_functions"
:hint "DEFUN: (defun name (params) body). The last form of the body is the return value. Twice X is (* 2 x), and addition is (+ a b).")
@@ -58,6 +89,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "functions4"
:dir "02_functions"
:hint "FLOOR returns two values at once: (floor 10 3) is 3 and 1. Pass it straight through. For 125 seconds: (floor seconds 60) is 2 minutes and 5 seconds.")
(:name "functions5"
:dir "02_functions"
:hint "VALUES hands back two answers at once: (values 2 65) is TWO values - a LIST is one value wearing brackets. FLOOR's first value is the dollars and (mod cents 100) the cents. HALF-AND-DOUBLE returns (/ n 2) and (* n 2) together.")
(:name "variables1"
:dir "03_variables"
:hint "DEFPARAMETER gives a global its value: (defparameter *room-capacity* 100). Any capacity from 3 to 199 passes both checks.")
@@ -82,6 +116,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "if4"
:dir "04_conditionals"
:hint "OR returns the first non-NIL value: (or a b c). For safe-div, UNLESS can guard the division and OR supplies the fallback: (or (unless (zerop b) (/ a b)) :undefined).")
(:name "if5"
:dir "04_conditionals"
:hint "CASE tests with EQL, so bare symbols work as keys: (case fruit ((apple banana) \"cheap\") ...). Group keys in one list; a (t ...) clause is the fallback. ECASE has no fallback - a miss signals a TYPE-ERROR, which the last check wants.")
(:name "pred1"
:dir "05_predicates"
:hint "Only NIL is false. (not (null thing)) is true for everything else, including 0 and the empty string.")
@@ -91,6 +128,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "pred3"
:dir "05_predicates"
:hint "Write a COND. Check (NULL V) before the others: (listp nil) is also true, so the :nothing branch must come first.")
(:name "pred4"
:dir "05_predicates"
:hint "EQL demands the same type too: (eql 1 1.0) is NIL. EQUALP is easygoing: numbers compare by value - (equalp 1 1.0) is T - and characters ignore case, so (equalp #\\a #\\A) is T.")
(:name "lists1"
:dir "06_lists"
:hint "CAR takes the first element, CDR takes the rest. To put one element in front, CONS it: (cons x xs) - (list x xs) would nest the list instead.")
@@ -106,6 +146,18 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "lists5"
:dir "06_lists"
:hint "ASSOC finds a pair by key: (assoc item *menu*) returns the pair; its CDR is the price. PUSH a new (cons item cost) pair onto the alist.")
(:name "lists6"
:dir "06_lists"
:hint "DESTRUCTURING-BIND is LET for list-shaped data: (destructuring-bind (w h d) dims (* w h d)). The dotted template (x . rest) splits head from tail. Two answers at once ride on (values x rest) - the check gathers them with MULTIPLE-VALUE-LIST.")
(:name "vectors1"
:dir "20_vectors"
:hint "Slots are numbered from 0: (aref v 1) is the second element. MAKE-ARRAY builds a row of a given size, VECTOR one from its arguments: (vector a b c) => #(A B C). SETF on AREF writes a slot.")
(:name "vectors2"
:dir "20_vectors"
:hint "A fill pointer counts the slots in use: (make-array 5 :fill-pointer 0) has room for five. VECTOR-PUSH stores past it and returns the index, or NIL when the row is full; VECTOR-PUSH-EXTEND grows the vector, so make it :adjustable.")
(:name "vectors3"
:dir "20_vectors"
:hint "A string is a vector of characters: (aref \"cat\" 0) returns the first one. MAKE-ARRAY with :element-type 'character builds strings. Before changing a string you were handed, build your own copy with MAKE-ARRAY :initial-contents.")
(:name "recurs1"
:dir "07_recursion"
:hint "The base case must return 0, not NIL - (+ 3 nil) is a type error. Add the head to the recursive sum of the rest.")
@@ -118,6 +170,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "recurs4"
:dir "07_recursion"
:hint "A tree has two parts: (car tree) and (cdr tree). Count the leaves in BOTH and add the results.")
(:name "recurs5"
:dir "07_recursion"
:hint "LABELS defines local functions that can call each other: (labels ((even-step (k) ... (odd-step (1- k))) (odd-step (k) ... (even-step (1- k)))) (even-step n)). Each step takes one off with (1- k) and hands the question to the other; zero answers T for even, NIL for odd.")
(:name "func1"
:dir "08_functional"
:hint "FUNCALL calls a function value: (funcall f 10). LAMBDA makes function values: (lambda (x) (* 2 x)).")
@@ -130,6 +185,22 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "func4"
:dir "08_functional"
:hint "REDUCE folds: (reduce #'max xs) for the biggest, (reduce #'* xs :initial-value 1) for the product.")
(:name "sequences1"
:dir "19_sequences"
:hint "FIND returns the element, POSITION its index, COUNT the matches: (position 'b '(a b c)) => 1. :test decides what matches; the default treats 1 and 1.0 as different, so use (find x xs :test #'=).")
(:name "sequences2"
:dir "19_sequences"
:hint "REMOVE drops matches: (remove x xs), mind the argument order. REMOVE-IF drops what its predicate accepts. SUBSTITUTE reads (NEW OLD SEQUENCE). EVERY wants the predicate true of all elements; SOME settles for one.")
(:name "sequences3"
:dir "19_sequences"
:hint "SORT takes the comparison first: (sort (list 3 1 2) #'<). With :key it compares one part of each element: (sort pairs #'< :key #'cdr). REVERSE returns a backwards copy - MAPCAR it over each word.")
(:name "sequences4"
:dir "19_sequences"
:hint "SEARCH finds a whole subsequence, not one element: (search '(b c) '(a b c d)) => 1. MERGE interleaves two already-sorted sequences: (merge 'list a b #'<). EVERY is true of the empty list; SOME is not.")
(:name "quiz1"
:dir "quizzes"
:hint ("APPEND makes a new book with the contact at the end."
"DOLIST + STRING-EQUAL + GETF finds by name; FORMAT makes the card."))
(:name "str1"
:dir "09_strings"
:hint "FORMAT's first argument NIL returns a string. ~a prints a value; ~10a pads it to ten columns.")
@@ -142,6 +213,27 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "str4"
:dir "09_strings"
:hint "FORMAT iterates with ~{ ... ~}, and ~^ skips the separator at the last element: (format nil \"~{~a~^, ~}\" xs).")
(:name "str5"
:dir "09_strings"
:hint "A colon modifier makes ~d group with commas: (format nil \"~:d widgets\" 1234567). A number after a comma fixes ~f's decimals: ~,2f keeps two - (format nil \"~a is about ~,2f\" label n) rounds pi to 3.14.")
(:name "str6"
:dir "09_strings"
:hint "~[ ~; ~] picks a branch by number: pass (mod n 2), with tick before the ~; and tock after. ~( ... ~) downcases what it wraps: (format nil \"~(~a~)\" s).")
(:name "str7"
:dir "09_strings"
:hint "~& only breaks the line when there is one to break: a fresh string gets no leading newline, where ~% always adds one. ~v@a takes the width from the arguments and right-justifies. Two fixed columns make the receipt: (format nil \"~8a~4@a\" item price).")
(:name "files1"
:dir "21_files"
:hint ":direction :output is what opens the file for writing - without it WITH-OPEN-FILE opens for INPUT and the write fails. :if-exists :supersede starts the file fresh every save. End SAVE-NOTE's body with T so the check sees a true value. To read back, open the file again and (READ in): READ takes the stream, not the file name.")
(:name "files2"
:dir "21_files"
:hint "READ-LINE returns the next line; (read-line in nil nil) hands you NIL instead of an error at the end. Then it is the recursion chapter's shape: NIL is the base case, (cons line (poem-rest in)) the step. No LOOP needed.")
(:name "files3"
:dir "21_files"
:hint "PRIN1 quotes strings and PRINC does not: (prin1 x s), then a (princ \" \" s), then (princ x s). PRINT is PRIN1 with a newline before and a space after - one call does the label line and its spacing.")
(:name "files4"
:dir "21_files"
:hint "The same shape as poem-rest: (read-line in nil nil) for NIL at the end, (parse-integer line) to turn each line into a number to add. For the junk: PARSE-INTEGER with :JUNK-ALLOWED T reads the leading number and answers NIL when there is none.")
(:name "loops1"
:dir "10_loops"
:hint "DOLIST walks a list: (dolist (x xs) (setf total (+ total x))). DOTIMES counts from 0; PUSH inside it builds the countdown naturally.")
@@ -151,6 +243,15 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "loops3"
:dir "10_loops"
:hint "WHEN filters inside LOOP: (loop for x in xs when (evenp x) collect x). THEREIS returns the first non-NIL value and stops: (thereis (if (> x 100) x)).")
(:name "loops4"
:dir "10_loops"
:hint "A FOR with THEN steps a value: (loop repeat n for x = 1 then (* x 2) collect x). For the cart keep the running total with WITH: (loop with total = 0 for p in xs until (>= (+ total p) cap) do (setf total (+ total p)) collect p) - the UNTIL watches the total, not the price.")
(:name "loops5"
:dir "10_loops"
:hint "DO steps every variable with the OLD values, like LET - so TOTAL's step must be (+ total i). DO* steps one at a time like LET*, and B's step (* b a) then sees A's NEW value - swap the factorial's DO for DO* and it multiplies the right pairs.")
(:name "loops6"
:dir "10_loops"
:hint "COUNT wants a test: (loop for x in xs count (oddp x)). MAXIMIZE tracks the biggest: (loop for x in xs maximize x), NIL when the loop never runs. For the wallet LOOP-FINISH bails out before the total goes over: (if (> (+ total x) limit) (loop-finish) (setf total (+ total x))), and FINALLY returns the total either way.")
(:name "num1"
:dir "11_numbers"
:hint "Drop the 2.0: (expt 2 100) and (/ 7 2) stay exact when all arguments are integers.")
@@ -160,6 +261,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "num3"
:dir "11_numbers"
:hint "Clamp with both bounds: (min high (max low x)). Distance is (abs (- a b)). INCF and DECF step a variable in place.")
(:name "num4"
:dir "11_numbers"
:hint "CHECK-TYPE is the live gate: (check-type n integer) signals a TYPE-ERROR when N is not one - the checks count on it. Compound types narrow the gate: (check-type n (integer 0 100)) lets in only whole numbers from 0 to 100.")
(:name "structs1"
:dir "12_structs"
:hint "The constructor takes a keyword for every slot: (make-person :name \"Ada\" :age 36). The reader is (person-age ada).")
@@ -181,6 +285,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "hash3"
:dir "13_hash_tables"
:hint "GETHASH takes a default: (gethash x table 0) counts missing keys as 0, so (incf (gethash x table 0)) tallies in one line.")
(:name "hash4"
:dir "13_hash_tables"
:hint "MAPHASH hands each pair to a function of KEY and VALUE - mind which is which. Total the stock by (incf total value). Collect keys with LET and PUSH inside the lambda: (maphash (lambda (key value) (push key keys)) table). The walk order is undefined, so the check only asks about length and membership.")
(:name "pkg1"
:dir "14_packages"
:hint "The function now lives in the SHAPES package; the body is just (* s s). The package form above already exported AREA so the checks can reach it.")
@@ -190,6 +297,12 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "pkg3"
:dir "14_packages"
:hint "STUDIO uses SHAPES, so AREA is right there: (+ (area a) (area b)).")
(:name "pkg4"
:dir "14_packages"
:hint "Name the package: (find-symbol name 'attic) - with no package argument it searches *package* and finds nothing. INTERN makes-or-finds: (intern name 'attic) answers with the symbol either way, so (symbol-name (attic-intern \"SPARE-KEY\")) is \"SPARE-KEY\".")
(:name "pkg5"
:dir "14_packages"
:hint "The double colon reaches internals: shop::secret-sale. For the clash, add (:shadow #:fill) to the defpackage - then FILL inside POST-OFFICE means POST-OFFICE's own, and COMMON-LISP's FILL still fills sequences, which the third check relies on. The nickname STORE reaches SHOP the single-colon way.")
(:name "clos1"
:dir "15_clos"
:hint "MAKE-INSTANCE with initargs: (make-instance 'dog :name \"Rex\" :tricks '(\"sit\" \"roll-over\")). Initargs are keywords named after the slots.")
@@ -202,6 +315,15 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "clos4"
:dir "15_clos"
:hint "The EQL-specialized method returns \"a free muffin too\" when CUSTOMER is exactly 'vip.")
(:name "clos5"
:dir "15_clos"
:hint "WITH-SLOTS turns slots into plain variables: (with-slots (x y) p (make-instance 'point :x (* x 2) :y (* y 2))). WITH-ACCESSORS names them by accessor: (with-accessors ((x point-x)) p (setf x (1+ x)) p) - SETF goes through the accessor.")
(:name "clos6"
:dir "15_clos"
:hint "CALL-NEXT-METHOD runs the method one step up and you build on its answer: (concatenate 'string (call-next-method) \" Woof!\"). With no method above, CALL-NEXT-METHOD itself errors - so ask first: (if (next-method-p) (call-next-method) \"Prrr\").")
(:name "clos7"
:dir "15_clos"
:hint "Class options ride after the slots list: (:default-initargs :x 0 :y 0) feeds X and Y their defaults, and :x 7 still overrides. To print nicely, define PRINT-OBJECT: (print-unreadable-object (p stream :type t) (format stream \"x=~a y=~a\" (point-x p) (point-y p))) - WITH-OUTPUT-TO-STRING plus PRINC lets the check watch.")
(:name "cond1"
:dir "16_conditions"
:hint "Wrap the call in HANDLER-CASE with a PARSE-ERROR clause that returns :not-a-number.")
@@ -214,6 +336,15 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "cond4"
:dir "16_conditions"
:hint "SAFE-CAR wraps its error in RESTART-CASE, offering (use-nil () nil). CAR-WITH-DEFAULT uses HANDLER-BIND and INVOKE-RESTART 'USE-NIL.")
(:name "cond5"
:dir "16_conditions"
:hint "The :REPORT option gives a condition its text: (:report \"The cart is empty - nothing to check out.\") - PRINC of the condition prints it, so the handler-case formats C with ~a. WARN does not unwind: after the warning the body carries on. SIGNAL is quiet the same way - your low-battery handler-case does the unwinding.")
(:name "cond6"
:dir "16_conditions"
:hint "Give the caller a way out: (restart-case (parse-integer text) (use-value (value) value)) - the handler upstairs then (invoke-restart 'use-value 42) and your restart answers with it. IGNORE-ERRORS is the quick cushion: (ignore-errors (parse-integer text)) is NIL when the parse goes wrong.")
(:name "quiz3"
:dir "quizzes"
:hint "Tally with DOLIST and (incf (gethash order table 0)); kitchen-count wants MULTIPLE-VALUE-BIND and (error 'not-ordered ...); a price is (cdr (assoc item menu)); the line is one FORMAT ~{ ~^ join, lowercased with STRING-DOWNCASE.")
(:name "macro1"
:dir "17_macros"
:hint "Return the code that should run: `(if ,test (progn ,@body)). MACROEXPAND-1 in a REPL shows what you built.")
@@ -226,6 +357,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "macro4"
:dir "17_macros"
:hint "LOOP does the work: `(loop while ,test do ,@body).")
(:name "macro5"
:dir "17_macros"
:hint "The reader function returns the object the text becomes: (list 'maybe (read stream)) wraps whatever follows the #?. With (read stream) alone, #?red reads as plain RED - the registration works, the wrapping is the fix.")
(:name "dyn1"
:dir "18_dynamic"
:hint "INCF the captured variable and return the result: (lambda () (incf count)). Each closure has its own COUNT.")
@@ -235,10 +369,9 @@ Found an issue, or want to add an exercise? Improvements welcome!")
(:name "dyn3"
:dir "18_dynamic"
:hint "MULTIPLE-VALUE-BIND on GETHASH: if PRESENT return the value, otherwise compute, SETF the table, return. The second call must not touch SLOW-FIB again.")
(:name "quiz1"
:dir "quizzes"
:hint ("APPEND makes a new book with the contact at the end."
"DOLIST + STRING-EQUAL + GETF finds by name; FORMAT makes the card."))
(:name "dyn4"
:dir "18_dynamic"
:hint "The second DEFVAR kept quiet - *cache* stayed 99 - while the second DEFPARAMETER rebound *config* back to 10. CURRENT-VALUES reads the two variables: (list *cache* *config*).")
(:name "quiz2"
:dir "quizzes"
:hint "A COND over three shapes: numbers, quote forms, and operator forms. MEMBER (car expr) '(+ - *) recognizes the operators; APPLY + MAPCAR evaluates the arguments."))))
+25
View File
@@ -0,0 +1,25 @@
;;; S-EXPRESSIONS 4: READER SHORTHAND (solution)
(defstruct point x y)
(defun the-adder ()
#'+)
(defun counting ()
#(1 2 3))
(defun origin ()
#s(point :x 1 :y 2))
(defun magic-web-number ()
#xdeadbeef)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (functionp (the-adder)))
(check (vectorp (counting)))
(check (point-p (origin)))
(check-equal 3735928559 (magic-web-number))
+17
View File
@@ -0,0 +1,17 @@
;;; FUNCTIONS 5: PRODUCING VALUES (solution)
(defun split-money (cents)
(values (floor cents 100) (mod cents 100)))
(defun half-and-double (n)
(values (/ n 2) (* n 2)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(2 65) (multiple-value-list (split-money 265)))
(check-equal '(0 5) (multiple-value-list (split-money 5)))
(check-equal '(3 12) (multiple-value-list (half-and-double 6)))
(check-equal '(7/2 14) (multiple-value-list (half-and-double 7)))
+26
View File
@@ -0,0 +1,26 @@
;;; CONDITIONALS 5: CASE AND ECASE (solution)
(defun rate-fruit (fruit)
(case fruit
((apple banana) "cheap")
((mango durian) "pricey")
(t "unknown")))
(defun door-state (state)
(ecase state
(:open "come in")
(:closed "knock first")))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "cheap" (rate-fruit 'apple))
(check-equal "cheap" (rate-fruit 'banana))
(check-equal "pricey" (rate-fruit 'mango))
(check-equal "pricey" (rate-fruit 'durian))
(check-equal "unknown" (rate-fruit 'kiwi))
(check-equal "come in" (door-state :open))
(check-equal "knock first" (door-state :closed))
(check-error (door-state :ajar) 'type-error)
+23
View File
@@ -0,0 +1,23 @@
;;; PREDICATES 4: EQL AND EQUALP (solution)
(defun same-exact-p (a b)
(eql a b))
(defun same-amount-p (a b)
(equalp a b))
(defun same-twin-p (a b)
(equalp a b))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (same-exact-p 7 7))
(check (not (same-exact-p 1 1.0)))
(check (not (same-exact-p 1 2)))
(check (same-amount-p 1 1.0))
(check (not (same-amount-p 1 2)))
(check (same-twin-p #\a #\A))
(check (not (same-twin-p #\a #\b)))
+19
View File
@@ -0,0 +1,19 @@
;;; LISTS 6: DESTRUCTURING-BIND (solution)
(defun dimensions (dims)
(destructuring-bind (w h d) dims
(* w h d)))
(defun first-and-rest (xs)
(destructuring-bind (x . rest) xs
(values x rest)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 60 (dimensions '(3 4 5)))
(check-equal 0 (dimensions '(0 10 2)))
(check-equal '(1 (2 3)) (multiple-value-list (first-and-rest '(1 2 3))))
(check-equal '(a ()) (multiple-value-list (first-and-rest '(a))))
+22
View File
@@ -0,0 +1,22 @@
;;; RECURSION 5: MUTUAL RECURSION (solution)
(defun my-evenp (n)
(labels ((even-step (k)
(if (zerop k)
t
(odd-step (1- k))))
(odd-step (k)
(if (zerop k)
nil
(even-step (1- k)))))
(even-step n)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (my-evenp 0))
(check (my-evenp 4))
(check (not (my-evenp 7)))
(check (not (my-evenp 1)))
+17
View File
@@ -0,0 +1,17 @@
;;; STRINGS 5: NUMBERS IN FORMAT (solution)
(defun price-tag (n)
(format nil "~:d widgets" n))
(defun fixed (label n)
(format nil "~a is about ~,2f" label n))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "1,234,567 widgets" (price-tag 1234567))
(check-equal "7 widgets" (price-tag 7))
(check-equal "pi is about 3.14" (fixed "pi" pi))
(check-equal "e is about 2.72" (fixed "e" 2.718281828))
+19
View File
@@ -0,0 +1,19 @@
;;; STRINGS 6: FORMAT PICKS AND CASE (solution)
(defun tick-tock (n)
(format nil "~[tick~;tock~]" (mod n 2)))
(defun quiet-title (s)
(format nil "~(~a~)" s))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "tick" (tick-tock 0))
(check-equal "tock" (tick-tock 1))
(check-equal "tick" (tick-tock 2))
(check-equal "tock" (tick-tock 5))
(check-equal "grace" (quiet-title "GRACE"))
(check-equal "ada lovelace" (quiet-title "ADA LOVELACE"))
+22
View File
@@ -0,0 +1,22 @@
;;; STRINGS 7: NEWLINES AND COLUMNS (solution)
(defun add-line (s)
(format nil "~&~a" s))
(defun right-column (name width)
(format nil "~v@a" width name))
(defun receipt (item price)
(format nil "~8a~4@a" item price))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "hi" (add-line "hi"))
(check-equal "parrot" (add-line "parrot"))
(check-equal " ada" (right-column "ada" 6))
(check-equal "hi" (right-column "hi" 2))
(check-equal "tea 2" (receipt "tea" 2))
(check-equal "coffee 3" (receipt "coffee" 3))
+25
View File
@@ -0,0 +1,25 @@
;;; LOOPS 4: LOOP'S OTHER CLAUSES (solution)
(defun doublings (n)
(loop repeat n
for x = 1 then (* x 2)
collect x))
(defun cart-until-cap (xs cap)
(loop with total = 0
for p in xs
until (>= (+ total p) cap)
do (setf total (+ total p))
collect p))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(1 2 4 8) (doublings 4))
(check-equal '(1) (doublings 1))
(check-equal '() (doublings 0))
(check-equal '(3 5) (cart-until-cap '(3 5 2 8) 10))
(check-equal '() (cart-until-cap '(20 1) 10))
(check-equal '(1 2) (cart-until-cap '(1 2 3 4) 6))
+24
View File
@@ -0,0 +1,24 @@
;;; LOOPS 5: DO AND DO* (solution)
(defun triangle-do (n)
(do ((i 1 (1+ i))
(total 0 (+ total i)))
((> i n) total)))
(defun factorial-of (n)
(do* ((a 1 (1+ a))
(b 1 (* b a)))
((>= a n) b)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 6 (triangle-do 3))
(check-equal 55 (triangle-do 10))
(check-equal 0 (triangle-do 0))
(check-equal 1 (factorial-of 0))
(check-equal 1 (factorial-of 1))
(check-equal 6 (factorial-of 3))
(check-equal 24 (factorial-of 4))
+35
View File
@@ -0,0 +1,35 @@
;;; LOOPS 6: COUNT, MAXIMIZE, LOOP-FINISH (solution)
(defun count-odds (xs)
(loop for x in xs
count (oddp x)))
(defun widest (xs)
(if (null xs)
nil
(loop for x in xs
maximize x)))
(defun first-sum-over (xs limit)
(loop with total = 0
for x in xs
do (if (> (+ total x) limit)
(loop-finish)
(setf total (+ total x)))
finally (return total)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 3 (count-odds '(1 2 3 4 5)))
(check-equal 0 (count-odds '(2 4)))
(check-equal 0 (count-odds '()))
(check-equal 9 (widest '(3 9 2)))
(check-equal 4 (widest '(4)))
(check-equal nil (widest '()))
(check-equal 5 (first-sum-over '(2 3 4) 8))
(check-equal 9 (first-sum-over '(2 3 4) 100))
(check-equal 0 (first-sum-over '(9 9) 8))
(check-equal 0 (first-sum-over '() 5))
+22
View File
@@ -0,0 +1,22 @@
;;; NUMBERS 4: TYPE DECLARATIONS (solution)
(defun counted-double (n)
(check-type n integer)
(* 2 n))
(defun shrink (n)
(check-type n (integer 0 100))
(- 100 n))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 10 (counted-double 5))
(check-equal 0 (counted-double 0))
(check-error (counted-double "five") 'type-error)
(check-equal 60 (shrink 40))
(check-equal 100 (shrink 0))
(check-error (shrink 200) 'type-error)
(check-error (shrink -3) 'type-error)
+34
View File
@@ -0,0 +1,34 @@
;;; HASH TABLES 4: MAPHASH (solution)
(defparameter *stock*
(let ((table (make-hash-table)))
(setf (gethash 'tea table) 2
(gethash 'coffee table) 3
(gethash 'cocoa table) 4)
table))
(defun stock-total ()
(let ((total 0))
(maphash (lambda (key value)
(incf total value))
*stock*)
total))
(defun keys-of (table)
(let ((keys '()))
(maphash (lambda (key value)
(push key keys))
table)
keys))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 9 (stock-total))
(check (let ((keys (keys-of *stock*)))
(and (= 3 (length keys))
(member 'tea keys)
(member 'coffee keys)
(member 'cocoa keys))))
+31
View File
@@ -0,0 +1,31 @@
;;; PACKAGES 4: FIND-SYMBOL AND INTERN (solution)
(defpackage #:attic
(:use #:common-lisp)
(:export #:heirloom))
(in-package #:attic)
(defun heirloom ()
'grandmas-ring)
(in-package #:common-lisp-user)
(defun attic-lookup (name)
(find-symbol name 'attic))
(defun attic-intern (name)
(intern name 'attic))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(attic:heirloom :external)
(multiple-value-list (attic-lookup "HEIRLOOM")))
(check-equal '(nil nil)
(multiple-value-list (attic-lookup "GHOST")))
(check (attic-intern "SPARE-KEY"))
(check-equal "SPARE-KEY" (symbol-name (attic-intern "SPARE-KEY")))
(check (eq 'attic:heirloom (attic-intern "HEIRLOOM")))
+41
View File
@@ -0,0 +1,41 @@
;;; PACKAGES 5: INTERNALS, NICKNAMES, SHADOWING (solution)
(defpackage #:shop
(:use #:common-lisp)
(:nicknames #:store)
(:export #:price))
(in-package #:shop)
(defun price ()
5)
(defun secret-sale ()
2)
(in-package #:common-lisp-user)
(defun best-deal ()
(shop::secret-sale))
(defpackage #:post-office
(:use #:common-lisp)
(:shadow #:fill))
(in-package #:post-office)
(defun fill (box)
(list 'stuffed box))
(in-package #:common-lisp-user)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 5 (store:price))
(check-equal 2 (best-deal))
(check-equal (list 0 0 0) (fill (list 1 2 3) 0))
(check-equal '(post-office::stuffed crate)
(funcall (find-symbol "FILL" '#:post-office) 'crate))
+26
View File
@@ -0,0 +1,26 @@
;;; CLOS 5: WITH-SLOTS AND WITH-ACCESSORS (solution)
(defclass point ()
((x :initarg :x :accessor point-x)
(y :initarg :y :accessor point-y)))
(defun double-point (p)
(with-slots (x y) p
(make-instance 'point :x (* x 2) :y (* y 2))))
(defun shift-x (p)
(with-accessors ((x point-x)) p
(setf x (1+ x)))
p)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (let ((q (double-point (make-instance 'point :x 3 :y 4))))
(and (eql 6 (point-x q)) (eql 8 (point-y q)))))
(check (let ((p (shift-x (make-instance 'point :x 1))))
(eql 2 (point-x p))))
(check (let ((p (shift-x (make-instance 'point :x 10))))
(eql 11 (point-x p))))
+29
View File
@@ -0,0 +1,29 @@
;;; CLOS 6: CALL-NEXT-METHOD AND NEXT-METHOD-P (solution)
(defclass animal () ())
(defclass dog (animal) ())
(defclass cat (animal) ())
(defgeneric announce (a))
(defmethod announce ((a animal))
"I am an animal.")
(defgeneric purr (a))
(defmethod announce ((d dog))
(concatenate 'string (call-next-method) " Woof!"))
(defmethod purr ((c cat))
(if (next-method-p)
(call-next-method)
"Prrr"))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "I am an animal. Woof!" (announce (make-instance 'dog)))
(check-equal "I am an animal." (announce (make-instance 'animal)))
(check-equal "Prrr" (purr (make-instance 'cat)))
+24
View File
@@ -0,0 +1,24 @@
;;; CLOS 7: PRINT-OBJECT AND DEFAULT-INITARGS (solution)
(defstruct candy filling size)
(defclass point ()
((x :initarg :x :accessor point-x)
(y :initarg :y :accessor point-y))
(:default-initargs :x 0 :y 0))
(defmethod print-object ((p point) stream)
(print-unreadable-object (p stream :type t)
(format stream "x=~a y=~a" (point-x p) (point-y p))))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 'swirl (candy-filling (make-candy :filling 'swirl)))
(check-equal 0 (point-x (make-instance 'point)))
(check-equal 7 (point-x (make-instance 'point :x 7)))
(check-equal "#<POINT x=3 y=4>"
(with-output-to-string (s)
(princ (make-instance 'point :x 3 :y 4) s)))
+40
View File
@@ -0,0 +1,40 @@
;;; CONDITIONS 5: REPORTS, WARN, SIGNAL (solution)
(define-condition low-battery (condition) ())
(define-condition empty-cart (error)
()
(:report "The cart is empty - nothing to check out."))
(defun checkout (items)
(when (null items)
(error 'empty-cart))
(list 'order items))
(defun battery-check (percent)
(when (< percent 20)
(warn "battery ~a%!" percent))
(list 'battery percent))
(defun check-battery (percent)
(when (<= percent 10)
(signal 'low-battery))
(list 'battery percent))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(order (milk)) (checkout '(milk)))
(check-error (checkout '()) 'empty-cart)
(check-equal "The cart is empty - nothing to check out."
(handler-case (checkout '())
(empty-cart (c) (format nil "~a" c))))
(check-equal '(battery 15) (battery-check 15))
(check-equal '(battery 90) (battery-check 90))
(check-equal :noticed (handler-case (warn "battery low")
(warning () :noticed)))
(check-equal :swapped (handler-case (check-battery 5)
(low-battery () :swapped)))
(check-equal '(battery 20) (check-battery 20))
+22
View File
@@ -0,0 +1,22 @@
;;; CONDITIONS 6: RESTARTS WITH ARGUMENTS, IGNORE-ERRORS (solution)
(defun parse-count (text)
(restart-case (parse-integer text)
(use-value (value)
value)))
(defun maybe-age (text)
(ignore-errors (parse-integer text)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 42 (handler-bind ((parse-error (lambda (c)
(declare (ignore c))
(invoke-restart 'use-value 42))))
(parse-count "abc")))
(check-equal 7 (parse-count "7"))
(check-equal 42 (maybe-age "42"))
(check-equal nil (maybe-age "abc"))
+15
View File
@@ -0,0 +1,15 @@
;;; MACROS 5: READER MACROS, A TASTER (solution)
(defun maybe-reader (stream sub-char num-arg)
(declare (ignore sub-char num-arg))
(list 'maybe (read stream)))
(set-dispatch-macro-character #\# #\? #'maybe-reader)
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(maybe red) '#?red)
(check-equal '(maybe (1 2)) '#?(1 2))
+22
View File
@@ -0,0 +1,22 @@
;;; DYNAMIC 4: DEFVAR VS DEFPARAMETER (solution)
(defvar *cache* 10)
(defparameter *config* 10)
(setf *cache* 99)
(setf *config* 99)
(defvar *cache* 10)
(defparameter *config* 10)
(defun current-values ()
(list *cache* *config*))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(99 10) (current-values))
(check-equal 99 *cache*)
(check-equal 10 *config*)
+25
View File
@@ -0,0 +1,25 @@
;;; SEQUENCES 1: FIND, POSITION, COUNT (solution)
(defun index-of (x xs)
(position x xs))
(defun occurrences (x xs)
(count x xs))
(defun find-same (x xs)
(find x xs :test #'=))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 1 (index-of 'b #(a b c)))
(check-equal 2 (index-of 3 '(1 2 3)))
(check-equal nil (index-of 9 '(1 2 3)))
(check-equal 3 (occurrences 'a #(a b a c a)))
(check-equal 2 (occurrences 'b '(a b a b a)))
(check-equal 0 (occurrences 5 '(1 2 3)))
(check-equal 1 (find-same 1.0 '(2 1 3)))
(check-equal 2 (find-same 2.0 '(1 2 3)))
(check-equal nil (find-same 9 '(1 2 3)))
+22
View File
@@ -0,0 +1,22 @@
;;; SEQUENCES 2: REMOVE, REMOVE-IF, SUBSTITUTE (solution)
(defun drop-them (x xs)
(remove x xs))
(defun drop-negatives (xs)
(remove-if #'minusp xs))
(defun swap-them (new old xs)
(substitute new old xs))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(a c) (drop-them 'b '(a b c b)))
(check-equal '(1 3) (drop-them 2 '(2 1 2 3 2)))
(check-equal '(1 0 2) (drop-negatives '(-1 1 0 -2 2)))
(check-equal '(3) (drop-negatives '(-5 -3 3)))
(check-equal '(x 2 x) (swap-them 'x 1 '(1 2 1)))
(check-equal '(a b a) (swap-them 'a 'z '(z b z)))
+25
View File
@@ -0,0 +1,25 @@
;;; SEQUENCES 3: SORT, :KEY, REVERSE (solution)
(defun ascending (xs)
(sort xs #'<))
(defun by-price (alist)
(sort alist #'< :key #'cdr))
(defun back-words (xs)
(mapcar #'reverse xs))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(1 2 3) (ascending (list 3 1 2)))
(check-equal '(-1 0 4) (ascending (list 4 0 -1)))
(check-equal '(3 2 1) (reverse (list 1 2 3)))
(check-equal '((tea . 1) (cola . 2))
(by-price (list (cons 'cola 2) (cons 'tea 1))))
(check-equal '((b . 1) (c . 2) (a . 7))
(by-price (list (cons 'a 7) (cons 'b 1) (cons 'c 2))))
(check-equal '("tac" "esaelp") (back-words '("cat" "please")))
(check-equal '("bba" "aa") (back-words '("abb" "aa")))
+27
View File
@@ -0,0 +1,27 @@
;;; SEQUENCES 4: EVERY, SOME, SEARCH, MERGE (solution)
(defun all-fit (f xs)
(every f xs))
(defun needle-at (needle hay)
(search needle hay))
(defun weave (a b)
(merge 'list a b #'<))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal t (all-fit #'plusp '(1 2 3)))
(check-equal nil (all-fit #'plusp '(-1 2 3)))
(check-equal t (all-fit #'plusp '()))
(check (some #'minusp '(1 -2 3)))
(check-equal 1 (needle-at '(b c) '(a b c d)))
(check-equal 2 (needle-at '(2 3) '(1 5 2 3)))
(check-equal 1 (needle-at "ana" "banana"))
(check-equal nil (needle-at '(9) '(1 2 3)))
(check-equal '(1 2 3 4) (weave (list 1 3) (list 2 4)))
(check-equal '(0 1 4 9) (weave (list 4) (list 0 1 9)))
(check-equal '(2 3) (weave (list 2 3) (list)))
+29
View File
@@ -0,0 +1,29 @@
;;; VECTORS 1: MAKE-ARRAY, AREF, AND #(...) (solution)
(defun slot-one (v)
(aref v 1))
(defun replace-first (v x)
(setf (aref v 0) x)
v)
(defun triple-vector (a b c)
(vector a b c))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 'b (slot-one #(a b c)))
(check-equal 2 (slot-one #(1 2 3)))
(check-equal 'x
(aref (replace-first (make-array 2 :initial-element 'a) 'x)
0))
(check-equal 99
(aref (replace-first (make-array 3 :initial-element 0) 99)
0))
(check (vectorp (triple-vector 'a 'b 'c)))
(check (equalp #(p q r) (triple-vector 'p 'q 'r)))
(check-equal 'q (aref (triple-vector 'p 'q 'r) 1))
(check-equal 3 (length #(a b c)))
+39
View File
@@ -0,0 +1,39 @@
;;; VECTORS 2: FILL POINTERS AND GROWING VECTORS (solution)
(defun blank-row (room)
(make-array room :fill-pointer 0))
(defun triple-push (v x)
(vector-push x v)
(vector-push x v)
(vector-push x v)
v)
(defun growable (a b)
(make-array 2 :initial-contents (list a b) :fill-pointer 2
:adjustable t))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal 0 (fill-pointer (blank-row 4)))
(check-equal 0 (vector-push 'z (blank-row 5)))
(check (let ((v (blank-row 3)))
(vector-push 'a v)
(equal 1 (fill-pointer v))))
(check-equal nil (vector-push 'x (make-array 2 :fill-pointer 2)))
(check-error (fill-pointer (make-array 3)))
(check-equal 3
(fill-pointer (triple-push (make-array 3 :fill-pointer 0)
'q)))
(check-equal 'q
(aref (triple-push (make-array 3 :fill-pointer 0) 'q)
2))
(check (let ((v (growable 'a 'b)))
(vector-push-extend 'c v)
(equal 'c (aref v 2))))
(check (let ((v (growable 1 2)))
(vector-push-extend 9 v)
(equal 9 (aref v 2))))
+29
View File
@@ -0,0 +1,29 @@
;;; VECTORS 3: STRINGS ARE VECTORS (solution)
(defun first-letter (w)
(aref w 0))
(defun retag (w c)
(let ((s (make-array (length w) :element-type 'character
:initial-contents w)))
(setf (aref s (- (length s) 1)) c)
s))
(defun letter-run (n c)
(make-array n :element-type 'character :initial-element c))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (vectorp "cat"))
(check-equal #\c (first-letter "cat"))
(check-equal #\a (first-letter "apple"))
(check-equal "cab" (retag "cat" #\b))
(check-equal "suns" (retag "sung" #\s))
(check (let ((w "cat"))
(retag w #\b)
(equal "cat" w)))
(check-equal "aaa" (letter-run 3 #\a))
(check-equal "xx" (letter-run 2 #\x))
+20
View File
@@ -0,0 +1,20 @@
;;; FILES 1: WITH-OPEN-FILE (solution)
(defparameter *note-file* "lisplings-note.txt")
(defun save-note ()
(with-open-file (out *note-file* :direction :output :if-exists :supersede)
(format out "(lisp is lovely)~%")
t))
(defun load-note ()
(with-open-file (in *note-file*)
(read in)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-note))
(check-equal '(lisp is lovely) (load-note))
+30
View File
@@ -0,0 +1,30 @@
;;; FILES 2: READING LINES (solution)
(defparameter *poem-file* "lisplings-poem.txt")
(defun save-poem ()
(with-open-file (out *poem-file* :direction :output :if-exists :supersede)
(format out "(lisp is life)~%")
(format out "lambda forever~%")
(format out "close the parens~%"))
t)
(defun poem-lines ()
(with-open-file (in *poem-file*)
(poem-rest in)))
(defun poem-rest (in)
(let ((line (read-line in nil nil)))
(if line
(cons line (poem-rest in))
nil)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-poem))
(check-equal '("(lisp is life)" "lambda forever" "close the parens")
(poem-lines))
(check-equal 3 (length (poem-lines)))
+22
View File
@@ -0,0 +1,22 @@
;;; FILES 3: PRINTING TO STREAMS (solution)
(defun two-views (x)
(with-output-to-string (s)
(prin1 x s)
(princ " " s)
(princ x s)))
(defun name-tag (name)
(with-output-to-string (s)
(print "name:" s)
(princ name s)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "\"hi\" hi" (two-views "hi"))
(check-equal "7 7" (two-views 7))
(check-equal "
\"name:\" ada" (name-tag "ada"))
+34
View File
@@ -0,0 +1,34 @@
;;; FILES 4: NUMBERS FROM FILES (solution)
(defparameter *count-file* "lisplings-counts.txt")
(defun save-counts ()
(with-open-file (out *count-file* :direction :output :if-exists :supersede)
(format out "10~%")
(format out "20~%")
(format out "5~%"))
t)
(defun sum-counts ()
(with-open-file (in *count-file*)
(sum-rest in)))
(defun sum-rest (in)
(let ((line (read-line in nil nil)))
(if line
(+ (parse-integer line) (sum-rest in))
0)))
(defun first-number (s)
(parse-integer s :junk-allowed t))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-counts))
(check-equal 35 (sum-counts))
(check-equal 12 (first-number "12 apples"))
(check-equal nil (first-number "no digits here"))
(check-error (parse-integer "12 apples") 'parse-error)
+50
View File
@@ -0,0 +1,50 @@
;;; QUIZ 3: THE LUNCH TALLY (solution)
(define-condition not-ordered (error)
((item :initarg :item :reader not-ordered-item))
(:documentation "Signaled when the kitchen is asked for an item nobody ordered."))
(defparameter *orders*
'(soup bread soup bread soup))
(defparameter *menu*
'((soup . 7) (bread . 3) (salad . 5)))
(defun tally-orders (orders)
(let ((table (make-hash-table)))
(dolist (order orders table)
(incf (gethash order table 0)))))
(defun kitchen-count (table item)
(multiple-value-bind (count present) (gethash item table)
(cond (present count)
(t (error 'not-ordered :item item)))))
(defun price-of (menu item)
(let ((pair (assoc item menu)))
(if pair (cdr pair) 0)))
(defun bill-total (orders menu)
(let ((total 0))
(dolist (order orders total)
(incf total (price-of menu order)))))
(defun order-line (items)
(string-downcase (format nil "~{~a~^, ~}" items)))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (let ((table (tally-orders *orders*)))
(and (eql 3 (gethash 'soup table))
(eql 2 (gethash 'bread table))
(eql 2 (hash-table-count table)))))
(check-equal 3 (kitchen-count (tally-orders *orders*) 'soup))
(check-error (kitchen-count (tally-orders *orders*) 'pizza) 'not-ordered)
(check-equal 7 (price-of *menu* 'soup))
(check-equal 0 (price-of *menu* 'pizza))
(check-equal 27 (bill-total *orders* *menu*))
(check-equal "soup, bread, salad" (order-line '(soup bread salad)))
(check-equal 0 (hash-table-count (tally-orders '())))