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

+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."))))