Wave 4: add sequences/vectors/files chapters, 23 exercises, quiz3, finish ceremony, PCL table
This commit is contained in:
1 parent
77843402fa
commit
4675bd1106
76 files changed
+2505
-14
No files matched your search
@@ -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))
|
||||
@@ -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)))
|
||||
@@ -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)
|
||||
@@ -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)))
|
||||
@@ -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))))
|
||||
@@ -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)))
|
||||
@@ -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))
|
||||
@@ -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"))
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
@@ -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))))
|
||||
@@ -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")))
|
||||
@@ -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))
|
||||
@@ -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))))
|
||||
@@ -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)))
|
||||
@@ -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)))
|
||||
@@ -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))
|
||||
@@ -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"))
|
||||
@@ -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))
|
||||
@@ -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*)
|
||||
@@ -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.
|
||||
@@ -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)))
|
||||
@@ -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)))
|
||||
@@ -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")))
|
||||
@@ -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)))
|
||||
@@ -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.
|
||||
@@ -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)))
|
||||
@@ -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))))
|
||||
@@ -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))
|
||||
@@ -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.
|
||||
@@ -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))
|
||||
@@ -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)))
|
||||
@@ -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"))
|
||||
@@ -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)
|
||||
@@ -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.
|
||||
@@ -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 '())))
|
||||
Reference in new issue
Block a user