Lisplings: Rustlings-style exercises for Common Lisp
70 exercises in 20 chapters, from first s-expressions to restarts, macros, CLOS, and a tiny Lisp interpreter. Each exercise ships broken with a solved twin and a hint. Includes a watch-mode runner, a plain-CL check harness, a nix flake, and verification tooling. All plain SBCL, no dependencies.
This commit is contained in:
commit
4df60ead93
172 files changed
+4403
No files matched your search
@@ -0,0 +1,28 @@
|
||||
;;; LISPLINGS
|
||||
;;;
|
||||
;;; This first exercise has no errors. It is here to show you the flow:
|
||||
;;;
|
||||
;;; 1. Lisplings is watching this file. Every time you save it, the
|
||||
;;; exercise runs again in the terminal.
|
||||
;;; 2. The exercises that follow contain an error: the file does not
|
||||
;;; load, or a check at the bottom fails. Your job is to fix them.
|
||||
;;; 3. When everything passes, press n in this terminal to move on.
|
||||
;;; 4. Stuck? Press h for a hint.
|
||||
;;;
|
||||
;;; Try it now: add a line to the banner below, save the file, and
|
||||
;;; watch what happens in the terminal.
|
||||
|
||||
(format t "~%")
|
||||
(format t " /~%")
|
||||
(format t " /~%")
|
||||
(format t " /~%")
|
||||
(format t " /\\~%")
|
||||
(format t " / \\~%")
|
||||
(format t "/ \\~%")
|
||||
(format t "~%")
|
||||
(format t " Welcome to Lisplings!~%")
|
||||
(format t " Small exercises to get you used to reading and~%")
|
||||
(format t " writing Common Lisp code.~%~%")
|
||||
(format t "This exercise is exercises/00_intro/intro1.lisp.~%")
|
||||
(format t "Edit it in your editor of choice and save; the output~%")
|
||||
(format t "appears here automatically. Press n when you are ready.~%")
|
||||
@@ -0,0 +1,11 @@
|
||||
;;; INTRO 2: READING AN ERROR
|
||||
;;;
|
||||
;;; This exercise does not run. Read the error in the terminal, then
|
||||
;;; fix it so the greeting prints.
|
||||
;;;
|
||||
;;; The ~a below is a format directive: "put a value here". But no
|
||||
;;; value was given after the format string...
|
||||
|
||||
(format t "Hello, ~a! Welcome to Common Lisp.~%")
|
||||
|
||||
(format t "Save this file with your fix; lisplings runs it again.~%")
|
||||
@@ -0,0 +1,12 @@
|
||||
# 01_sexps
|
||||
|
||||
S-expressions: prefix notation, nesting, and `quote`.
|
||||
|
||||
Everything in Lisp is built from parenthesized forms with the operator
|
||||
first. No precedence rules, no ambiguity: the shape of the code is the
|
||||
shape of the data. `quote` is the first taste of that.
|
||||
|
||||
Lispy things to try as you go:
|
||||
|
||||
- Start a second terminal, run `sbcl`, and poke at the forms there.
|
||||
- `(/ 1 2)` gives `1/2`. Lisp keeps fractions exact.
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; S-EXPRESSIONS 1: PREFIX NOTATION
|
||||
;;;
|
||||
;;; In Lisp the operator comes first: (+ 1 2) is 3. Nesting needs no
|
||||
;;; precedence rules at all: (* 2 (+ 3 4)) is 14.
|
||||
;;;
|
||||
;;; Fix each definition.
|
||||
|
||||
;; TODO: Add 10 and 32.
|
||||
(defun add-ten-and-thirty-two ()
|
||||
(10 + 32))
|
||||
|
||||
;; TODO: Multiply 6 by 7.
|
||||
(defun six-times-seven ()
|
||||
(+ 6 7))
|
||||
|
||||
;; TODO: Subtract 50 from 100.
|
||||
(defun fifty-from-one-hundred ()
|
||||
(- 50 100))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 42 (add-ten-and-thirty-two))
|
||||
(check-equal 42 (six-times-seven))
|
||||
(check-equal 50 (fifty-from-one-hundred))
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; S-EXPRESSIONS 2: NESTING AND EXACT MATH
|
||||
;;;
|
||||
;;; Inner expressions evaluate first: (* 2 (+ 3 4)) => (* 2 7) => 14.
|
||||
;;;
|
||||
;;; A Lisp delight: division is exact. (/ 1 2) is the rational 1/2,
|
||||
;;; not 0.5. Integers, rationals and floats form one number tower.
|
||||
|
||||
;; TODO: (2 + 3) multiplied by (4 - 1). Should be 15.
|
||||
(defun calc-a ()
|
||||
(+ (* 2 3) (- 4 1)))
|
||||
|
||||
;; TODO: 100 divided by the sum of 2 and 3. Should be 20.
|
||||
(defun calc-b ()
|
||||
(/ 100 2))
|
||||
|
||||
;; TODO: One half, as an exact rational.
|
||||
(defun one-half ()
|
||||
(/ 1 2.0))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 15 (calc-a))
|
||||
(check-equal 20 (calc-b))
|
||||
(check-equal 1/2 (one-half))
|
||||
@@ -0,0 +1,30 @@
|
||||
;;; S-EXPRESSIONS 3: QUOTE
|
||||
;;;
|
||||
;;; Code and data share one shape: the s-expression. QUOTE stops
|
||||
;;; evaluation and hands the expression back as data:
|
||||
;;;
|
||||
;;; (+ 1 2) evaluates to 3
|
||||
;;; '(+ 1 2) evaluates to the list (+ 1 2)
|
||||
;;;
|
||||
;;; 'x is reader shorthand for (quote x).
|
||||
|
||||
;; TODO: The form itself, not its value.
|
||||
(defun the-form ()
|
||||
(+ 1 2))
|
||||
|
||||
;; TODO: The symbol hello, not a variable lookup.
|
||||
(defun the-symbol ()
|
||||
hello)
|
||||
|
||||
;; TODO: The list (a b c), not a call to a.
|
||||
(defun the-list ()
|
||||
(a b c))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(+ 1 2) (the-form))
|
||||
(check-equal 'hello (the-symbol))
|
||||
(check-equal '(a b c) (the-list))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 02_functions
|
||||
|
||||
DEFUN, arity, optional and keyword arguments, and multiple values.
|
||||
|
||||
The return value is simply the last form of the body - no `return`
|
||||
keyword needed. Extra return values ride along with VALUES, and
|
||||
functions like FLOOR hand them out for free.
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; FUNCTIONS 1: DEFUN
|
||||
;;;
|
||||
;;; (defun name (parameters) body...)
|
||||
;;;
|
||||
;;; The body may hold many forms; they run in order, and the LAST
|
||||
;;; one is the return value.
|
||||
|
||||
;; TODO: Return twice the argument.
|
||||
(defun twice (x)
|
||||
x)
|
||||
|
||||
;; TODO: Add the two arguments.
|
||||
(defun add (a b)
|
||||
a)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 10 (twice 5))
|
||||
(check-equal -6 (twice -3))
|
||||
(check-equal 7 (add 3 4))
|
||||
(check-equal 0 (add 0 0))
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; FUNCTIONS 2: ARITY AND ORDER
|
||||
;;;
|
||||
;;; Lisp checks how many arguments you pass, and its error messages
|
||||
;;; say exactly what went wrong. Read them carefully.
|
||||
|
||||
;; TODO: The calls below pass TWO numbers. Give average the right
|
||||
;;; parameter list, and make it return their average.
|
||||
(defun average (a b c)
|
||||
(/ (+ a b c) 3))
|
||||
|
||||
;; TODO: (subtract 9 4) should be 5. Mind which way round you wrote
|
||||
;;; the subtraction.
|
||||
(defun subtract (minuend subtrahend)
|
||||
(- subtrahend minuend))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 3 (average 2 4))
|
||||
(check-equal 0 (average 0 0))
|
||||
(check-equal 5 (subtract 9 4))
|
||||
(check-equal -5 (subtract 4 9))
|
||||
@@ -0,0 +1,26 @@
|
||||
;;; FUNCTIONS 3: OPTIONAL AND KEYWORD ARGUMENTS
|
||||
;;;
|
||||
;;; (defun f (word &optional (n 2)) ...) N is optional, defaults to 2.
|
||||
;;; (defun g (x &key (y x)) ...) Call as (g 3 :y 5); a
|
||||
;;; default may use an
|
||||
;;; earlier parameter.
|
||||
|
||||
;; TODO: Repeat WORD N times. N is optional and defaults to 2.
|
||||
(defun repeat-word (word n)
|
||||
(make-list n :initial-element word))
|
||||
|
||||
;; TODO: Describe a box: WIDTH is required; :HEIGHT and :DEPTH are
|
||||
;;; keywords, both defaulting to the width.
|
||||
(defun make-box (width &key height depth)
|
||||
(list :width width :height height :depth depth))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '("hi" "hi") (repeat-word "hi"))
|
||||
(check-equal '("hi" "hi" "hi" "hi") (repeat-word "hi" 4))
|
||||
(check-equal '(:width 2 :height 2 :depth 2) (make-box 2))
|
||||
(check-equal '(:width 2 :height 5 :depth 2) (make-box 2 :height 5))
|
||||
(check-equal '(:width 2 :height 5 :depth 7) (make-box 2 :height 5 :depth 7))
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; FUNCTIONS 4: MULTIPLE VALUES
|
||||
;;;
|
||||
;;; A function may return several values at once:
|
||||
;;; (values 1 2) => 1 and 2
|
||||
;;; Everything except the first value rides along, waiting for
|
||||
;;; MULTIPLE-VALUE-BIND or NTH-VALUE to pick it up. FLOOR is a
|
||||
;;; classic: (floor 10 3) returns 3 AND 1.
|
||||
|
||||
;; TODO: Return TWO values: the whole part of A/B and the rest.
|
||||
(defun divide (a b)
|
||||
(/ a b))
|
||||
|
||||
;; TODO: Return TWO values: whole minutes, and leftover seconds.
|
||||
(defun split-seconds (seconds)
|
||||
seconds)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(3 1) (multiple-value-list (divide 10 3)))
|
||||
(check-equal '(3 1) (multiple-value-list (divide 7 2)))
|
||||
(check-equal '(2 5) (multiple-value-list (split-seconds 125)))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 03_variables
|
||||
|
||||
DEFPARAMETER, LET and LET*, shadowing, and SETF on places.
|
||||
|
||||
Globals conventionally wear earmuffs: `*room-capacity*`. SETF assigns
|
||||
to any place, from plain variables to list positions and properties.
|
||||
@@ -0,0 +1,18 @@
|
||||
;;; VARIABLES 1: GIVING A NAME TO A VALUE
|
||||
;;;
|
||||
;;; DEFPARAMETER introduces a global variable. By convention globals
|
||||
;;; wear earmuffs: *room-capacity*.
|
||||
|
||||
;; TODO: The function below needs *room-capacity* to exist. Give it a
|
||||
;;; value that makes 200 visitors a full room, but 3 visitors not.
|
||||
|
||||
(defun room-full-p (attendees)
|
||||
(> attendees *room-capacity*))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (room-full-p 200))
|
||||
(check (not (room-full-p 3)))
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; VARIABLES 2: LET AND SHADOWING
|
||||
;;;
|
||||
;;; LET creates local variables that exist only inside it. An inner
|
||||
;;; LET may reuse a name: the new binding shadows the old one, and
|
||||
;;; the initializer still evaluates in the outer scope.
|
||||
|
||||
;; TODO: The inner X should be the outer X plus 5 - make it so,
|
||||
;;; without changing either number.
|
||||
(defun shadow-add ()
|
||||
(let ((x 15))
|
||||
(let ((x 15))
|
||||
x)))
|
||||
|
||||
;; TODO: Make wrap-me return 20 by introducing a local variable.
|
||||
(defun wrap-me ()
|
||||
(+ x 5))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 20 (shadow-add))
|
||||
(check-equal 20 (wrap-me))
|
||||
@@ -0,0 +1,18 @@
|
||||
;;; VARIABLES 3: LET AND LET*
|
||||
;;;
|
||||
;;; LET binds everything at once: no initializer sees the others.
|
||||
;;; LET* binds one at a time: each may use the ones before it.
|
||||
|
||||
;; TODO: A should be 3, B should be A plus 2, and the function
|
||||
;;; returns A times B.
|
||||
(defun area-ish ()
|
||||
(let ((a 3)
|
||||
(b (+ a 2)))
|
||||
(* a b)))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 15 (area-ish))
|
||||
@@ -0,0 +1,20 @@
|
||||
;;; VARIABLES 4: SETF ON PLACES
|
||||
;;;
|
||||
;;; SETF assigns to any "place": a variable, a list element, a
|
||||
;;; property. The general shape is (setf PLACE new-value).
|
||||
|
||||
(defparameter *account* (list :owner "Ada" :balance 100))
|
||||
|
||||
;; TODO: Deposit should ADD the amount to the balance, not replace
|
||||
;;; it.
|
||||
(defun deposit (amount)
|
||||
(setf (getf *account* :balance) amount)
|
||||
*account*)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(:owner "Ada" :balance 150) (deposit 50))
|
||||
(check-equal '(:owner "Ada" :balance 170) (deposit 20))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 04_conditionals
|
||||
|
||||
IF, COND, WHEN, UNLESS, and the value-returning AND and OR.
|
||||
|
||||
NIL is the only false value. Zero and the empty string are true, and
|
||||
the empty list IS nil - watch for that one.
|
||||
@@ -0,0 +1,22 @@
|
||||
;;; CONDITIONALS 1: IF
|
||||
;;;
|
||||
;;; (if condition then-form else-form)
|
||||
;;;
|
||||
;;; Exactly one then, at most one else. And the golden rule: NIL is
|
||||
;;; the only false value. Zero, the empty string, everything else:
|
||||
;;; all TRUE.
|
||||
|
||||
;; TODO: "hot" above 30 degrees, "pleasant" otherwise.
|
||||
(defun classify (temperature)
|
||||
(if temperature
|
||||
"hot"
|
||||
"pleasant"))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "hot" (classify 35))
|
||||
(check-equal "pleasant" (classify 20))
|
||||
(check-equal "hot" (classify 31))
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; CONDITIONALS 2: COND
|
||||
;;;
|
||||
;;; IF cannot chain: it takes one test, one then, one else. For many
|
||||
;;; branches there is COND:
|
||||
;;;
|
||||
;;; (cond ((test-1) result-1)
|
||||
;;; ((test-2) result-2)
|
||||
;;; (t fallback))
|
||||
|
||||
;; TODO: describe-number should answer "zero", "negative" or
|
||||
;;; "positive". The IF below is malformed; rewrite with COND.
|
||||
(defun describe-number (n)
|
||||
(if (zerop n)
|
||||
"zero"
|
||||
(if (minusp n)
|
||||
"negative"
|
||||
"positive"
|
||||
"something else")))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "zero" (describe-number 0))
|
||||
(check-equal "negative" (describe-number -5))
|
||||
(check-equal "positive" (describe-number 3))
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; CONDITIONALS 3: WHEN AND UNLESS
|
||||
;;;
|
||||
;;; WHEN runs its body when the test is true, and returns NIL
|
||||
;;; otherwise. UNLESS runs it when the test is false. Both take a
|
||||
;;; whole body of forms, but no else.
|
||||
|
||||
;; TODO: Squares of positives only: negative input gives NIL.
|
||||
(defun only-positive-squares (n)
|
||||
(when (minusp n)
|
||||
(* n n)))
|
||||
|
||||
;; TODO: :welcome when the door is open, :denied when it is not.
|
||||
(defun enter (door-open-p)
|
||||
(unless door-open-p
|
||||
:welcome))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal nil (only-positive-squares -3))
|
||||
(check-equal 9 (only-positive-squares 3))
|
||||
(check-equal :welcome (enter t))
|
||||
(check-equal :denied (enter nil))
|
||||
@@ -0,0 +1,26 @@
|
||||
;;; CONDITIONALS 4: AND AND OR
|
||||
;;;
|
||||
;;; AND and OR are conditionals that return values. AND stops at the
|
||||
;;; first NIL and returns it; otherwise it returns the last value.
|
||||
;;; OR stops at the first non-NIL and returns it. Nothing after the
|
||||
;;; stop is evaluated at all.
|
||||
|
||||
;; TODO: The first non-NIL argument, or NIL.
|
||||
(defun first-truthy (a b c)
|
||||
a)
|
||||
|
||||
;; TODO: A/B when B is not zero, else :undefined. Keep it lazy: the
|
||||
;;; division must never happen for a zero B.
|
||||
(defun safe-div (a b)
|
||||
(/ a b))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 2 (first-truthy nil 2 3))
|
||||
(check-equal 3 (first-truthy nil nil 3))
|
||||
(check-equal nil (first-truthy nil nil nil))
|
||||
(check-equal 5 (safe-div 10 2))
|
||||
(check-equal :undefined (safe-div 10 0))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 05_predicates
|
||||
|
||||
Truthiness, the EQ/EQL/EQUAL/EQUALP ladder, and type predicates.
|
||||
|
||||
The empty list IS nil; everything else has some truth in it. Numbers
|
||||
compare by value with `=`, so (= 1 1.0) is T while (eql 1 1.0) is NIL.
|
||||
@@ -0,0 +1,18 @@
|
||||
;;; PREDICATES 1: WHAT IS TRUE?
|
||||
;;;
|
||||
;;; Only NIL is false. Zero is true. The empty string is true. And
|
||||
;;; the empty list... IS nil. Watch for that one.
|
||||
|
||||
;; TODO: T when THING counts as true, NIL otherwise.
|
||||
(defun truthy-p (thing)
|
||||
(not thing))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (truthy-p 0))
|
||||
(check (truthy-p ""))
|
||||
(check (not (truthy-p nil)))
|
||||
(check (not (truthy-p '())))
|
||||
@@ -0,0 +1,26 @@
|
||||
;;; PREDICATES 2: THE COMPARISON LADDER
|
||||
;;;
|
||||
;;; EQ same object.
|
||||
;;; EQL same object, or same number or character.
|
||||
;;; EQUAL EQL, plus structural strings and lists.
|
||||
;;; EQUALP EQUAL, case-insensitively, and (equalp 1 1.0) is T.
|
||||
;;; Numbers have their own: (= 1 1.0) is T.
|
||||
|
||||
;; TODO: True when the two lists have the same elements in order.
|
||||
(defun same-list-p (a b)
|
||||
(eq a b))
|
||||
|
||||
;; TODO: True when the two numbers are equal in value, 1 and 1.0
|
||||
;;; included.
|
||||
(defun same-number-p (a b)
|
||||
(eql a b))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (same-list-p (list 1 2 3) (list 1 2 3)))
|
||||
(check (not (same-list-p (list 1 2 3) (list 1 3 2))))
|
||||
(check (same-number-p 1 1.0))
|
||||
(check (not (same-number-p 1 2)))
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; PREDICATES 3: ASKING ABOUT TYPES
|
||||
;;;
|
||||
;;; The language answers questions: NUMBERP STRINGP SYMBOLP CONSP
|
||||
;;; LISTP NULL... and TYPEP is the general one:
|
||||
;;; (typep 3 'integer) => T
|
||||
;;;
|
||||
;;; One trap: (listp nil) is T. Order your branches accordingly.
|
||||
|
||||
;; TODO: A tag for each value: :number for numbers, :string for
|
||||
;;; strings, :list for lists, :nothing for nil, :other for the rest.
|
||||
(defun describe-value (v)
|
||||
(if (numberp v)
|
||||
:number
|
||||
:other))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal :number (describe-value 3))
|
||||
(check-equal :string (describe-value "hi"))
|
||||
(check-equal :list (describe-value '(a b)))
|
||||
(check-equal :nothing (describe-value nil))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 06_lists
|
||||
|
||||
CONS cells, CAR and CDR, list building, association lists.
|
||||
|
||||
A list is a chain of pairs ending in NIL. Quote writes lists as data;
|
||||
LIST and CONS build them at runtime. Association lists map keys to
|
||||
values with nothing but pairs.
|
||||
@@ -0,0 +1,29 @@
|
||||
;;; LISTS 1: CONS, CAR, CDR
|
||||
;;;
|
||||
;;; A list is a chain of CONS cells: (cons 1 (cons 2 nil)) is (1 2).
|
||||
;;; CAR takes the first element; CDR takes the rest.
|
||||
;;; (car '(1 2 3)) => 1
|
||||
;;; (cdr '(1 2 3)) => (2 3)
|
||||
;;; (cons 0 '(1 2)) => (0 1 2)
|
||||
|
||||
;; TODO: The first element of XS.
|
||||
(defun first-of (xs)
|
||||
(cdr xs))
|
||||
|
||||
;; TODO: The list without its first element.
|
||||
(defun rest-of (xs)
|
||||
(car xs))
|
||||
|
||||
;; TODO: A new list with X in front of XS.
|
||||
(defun prepend (x xs)
|
||||
(list x xs))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 1 (first-of '(1 2 3)))
|
||||
(check-equal '(2 3) (rest-of '(1 2 3)))
|
||||
(check-equal '(0 1 2) (prepend 0 '(1 2)))
|
||||
(check-equal '(a) (prepend 'a nil))
|
||||
@@ -0,0 +1,26 @@
|
||||
;;; LISTS 2: LIST, QUOTE, AND APPEND
|
||||
;;;
|
||||
;;; LIST builds a fresh list at runtime: (list 1 2 3).
|
||||
;;; QUOTE writes one down as data: '(1 2 3).
|
||||
;;; APPEND glues lists together: (append '(1 2) '(3 4)) => (1 2 3 4).
|
||||
|
||||
;; TODO: The list (a b c), written with a single quote.
|
||||
(defun abc ()
|
||||
(list 'a 'b))
|
||||
|
||||
;; TODO: The list (1 2 3), built by LIST.
|
||||
(defun one-two-three ()
|
||||
(list 1 '(2 3)))
|
||||
|
||||
;; TODO: The list (1 2 3 4): two lists joined with APPEND.
|
||||
(defun joined ()
|
||||
(cons '(1 2) '(3 4)))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(a b c) (abc))
|
||||
(check-equal '(1 2 3) (one-two-three))
|
||||
(check-equal '(1 2 3 4) (joined))
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; LISTS 3: ELEMENTS BY POSITION
|
||||
;;;
|
||||
;;; (nth 0 '(a b c)) => a ; counting starts at zero
|
||||
;;; (last '(1 2 3)) => (3) ; the LAST CONS, not the element
|
||||
;;; (butlast '(1 2 3)) => (1 2) ; everything but the last element
|
||||
|
||||
;; TODO: The first element of XS.
|
||||
(defun my-first (xs)
|
||||
(nth 1 xs))
|
||||
|
||||
;; TODO: The last ELEMENT of XS (careful with LAST).
|
||||
(defun my-last (xs)
|
||||
(last xs))
|
||||
|
||||
;; TODO: Everything except the last element.
|
||||
(defun drop-last (xs)
|
||||
(cdr xs))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 'a (my-first '(a b c)))
|
||||
(check-equal 'c (my-last '(a b c)))
|
||||
(check-equal '(a b) (drop-last '(a b c)))
|
||||
(check-equal nil (drop-last '(a)))
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; LISTS 4: PUSH AND POP
|
||||
;;;
|
||||
;;; PUSH and POP work on a variable holding a list:
|
||||
;;; (push x ys) is (setf ys (cons x ys))
|
||||
;;; (pop ys) removes and returns the first element
|
||||
|
||||
;; TODO: Push 0 onto XS, then push 1 onto that: the result begins
|
||||
;;; with (1 0 ...).
|
||||
(defun push-two (xs)
|
||||
(let ((ys xs))
|
||||
(push 0 ys)
|
||||
ys))
|
||||
|
||||
;; TODO: Return XS without its first two elements, using POP.
|
||||
(defun skip-two (xs)
|
||||
(let ((ys xs))
|
||||
ys))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(1 0 a b) (push-two '(a b)))
|
||||
(check-equal '(c d) (skip-two '(a b c d)))
|
||||
@@ -0,0 +1,29 @@
|
||||
;;; LISTS 5: ASSOCIATION LISTS
|
||||
;;;
|
||||
;;; An alist maps keys to values with a list of (key . value) pairs:
|
||||
;;; (assoc 'a '((a . 1) (b . 2))) => (a . 1)
|
||||
;;; (cdr (assoc 'a ...)) => 1
|
||||
|
||||
(defparameter *menu*
|
||||
'((coffee . 3) (tea . 2) (cocoa . 4)))
|
||||
|
||||
;; TODO: The price of a menu item; NIL when it is not served.
|
||||
(defun price (item)
|
||||
(car (assoc item *menu*)))
|
||||
|
||||
;; TODO: Add a new (ITEM . COST) pair to the menu, in front, and
|
||||
;;; return the menu.
|
||||
(defun add-item (item cost)
|
||||
*menu*)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 3 (price 'coffee))
|
||||
(check-equal 2 (price 'tea))
|
||||
(check-equal nil (price 'chai))
|
||||
(check (let ((menu (add-item 'chai 5)))
|
||||
(and (eql 5 (price 'chai))
|
||||
(eql 3 (price 'coffee)))))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 07_recursion
|
||||
|
||||
Lists and recursion grew up together.
|
||||
|
||||
The shape is always the same: a base case for NIL, a step that
|
||||
consumes one element, and trust that the rest is already solved.
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; RECURSION 1: SUMMING A LIST
|
||||
;;;
|
||||
;;; The classic shape - a base case, and a step that trusts the
|
||||
;;; recursive call:
|
||||
;;;
|
||||
;;; (defun sum (xs)
|
||||
;;; (if (null xs)
|
||||
;;; 0
|
||||
;;; (+ (car xs) (sum (cdr xs)))))
|
||||
|
||||
;; TODO: Sum the numbers in XS.
|
||||
(defun sum (xs)
|
||||
(if (null xs)
|
||||
nil
|
||||
(+ (car xs) (sum (cdr xs)))))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 6 (sum '(1 2 3)))
|
||||
(check-equal 0 (sum '()))
|
||||
(check-equal 10 (sum '(1 2 3 4)))
|
||||
@@ -0,0 +1,18 @@
|
||||
;;; RECURSION 2: LENGTH
|
||||
;;;
|
||||
;;; The same shape, counting instead of adding.
|
||||
|
||||
;; TODO: Count the elements of XS.
|
||||
(defun my-length (xs)
|
||||
(if (null xs)
|
||||
0
|
||||
(my-length (cdr xs))))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 0 (my-length '()))
|
||||
(check-equal 3 (my-length '(a b c)))
|
||||
(check-equal 5 (my-length '(1 2 3 4 5)))
|
||||
@@ -0,0 +1,21 @@
|
||||
;;; RECURSION 3: MEMBERSHIP
|
||||
;;;
|
||||
;;; MEMBER returns the tail of the list starting at the match:
|
||||
;;; (member 2 '(1 2 3)) => (2 3)
|
||||
;;; Your job is to rebuild that convention by hand.
|
||||
|
||||
;; TODO: Like MEMBER: return the tail of XS that starts with X, or
|
||||
;;; NIL when X is nowhere in XS.
|
||||
(defun my-member (x xs)
|
||||
(cond ((null xs) nil)
|
||||
((equal x (car xs)) t)
|
||||
(t (my-member x (cdr xs)))))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(b c) (my-member 'b '(a b c)))
|
||||
(check-equal nil (my-member 'z '(a b c)))
|
||||
(check-equal '(1 2 3) (my-member 1 '(1 2 3)))
|
||||
@@ -0,0 +1,20 @@
|
||||
;;; RECURSION 4: WALKING A TREE
|
||||
;;;
|
||||
;;; Lists nest, and a tree has TWO recursive parts: the first
|
||||
;;; element and the rest. Recurse into both.
|
||||
|
||||
;; TODO: Count the leaves (non-NIL atoms) of a nested list.
|
||||
(defun count-leaves (tree)
|
||||
(cond ((null tree) 0)
|
||||
((atom tree) 1)
|
||||
(t (count-leaves (car tree)))))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 0 (count-leaves '()))
|
||||
(check-equal 3 (count-leaves '(a b c)))
|
||||
(check-equal 4 (count-leaves '(1 (2 3) 4)))
|
||||
(check-equal 2 (count-leaves '((x) (y))))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 08_functional
|
||||
|
||||
LAMBDA, FUNCALL, APPLY, MAPCAR, REDUCE.
|
||||
|
||||
Functions are values here. Pass them, store them, build them with
|
||||
LAMBDA, and let MAPCAR and REDUCE do the iterating.
|
||||
@@ -0,0 +1,23 @@
|
||||
;;; FUNCTIONAL 1: LAMBDA AND FUNCALL
|
||||
;;;
|
||||
;;; (lambda (x) (* x x)) is a function VALUE, like any other value.
|
||||
;;; FUNCALL calls it: (funcall (lambda (x) (* x x)) 5) => 25.
|
||||
;;; #'car is reader shorthand for (function car), also a value.
|
||||
|
||||
;; TODO: Call F with 10 and return the result.
|
||||
(defun apply-to-ten (f)
|
||||
f)
|
||||
|
||||
;; TODO: Return a function (as a value) that doubles its argument.
|
||||
(defun doubler ()
|
||||
(lambda (x) x))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 100 (apply-to-ten (lambda (x) (* x x))))
|
||||
(check-equal 10 (apply-to-ten (lambda (x) (- x 0))))
|
||||
(check-equal 8 (funcall (doubler) 4))
|
||||
(check-equal -2 (funcall (doubler) -1))
|
||||
@@ -0,0 +1,22 @@
|
||||
;;; FUNCTIONAL 2: MAPCAR
|
||||
;;;
|
||||
;;; MAPCAR applies a function to each element and collects the
|
||||
;;; results into a new list:
|
||||
;;; (mapcar #'1+ '(1 2 3)) => (2 3 4)
|
||||
|
||||
;; TODO: Every element of XS, doubled.
|
||||
(defun double-all (xs)
|
||||
(mapcar #'1+ xs))
|
||||
|
||||
;; TODO: The names, uppercased.
|
||||
(defun shout-names (names)
|
||||
names)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(2 4 6) (double-all '(1 2 3)))
|
||||
(check-equal '(0) (double-all '(0)))
|
||||
(check-equal '("ADA" "GRACE") (shout-names '("ada" "grace")))
|
||||
@@ -0,0 +1,23 @@
|
||||
;;; FUNCTIONAL 3: FUNCALL AND APPLY
|
||||
;;;
|
||||
;;; FUNCALL spells the arguments out; APPLY takes the last of them
|
||||
;;; from a list:
|
||||
;;; (apply #'+ 1 2 '(3 4)) => 10
|
||||
|
||||
;; TODO: Add up all of XS, using APPLY.
|
||||
(defun sum-of (xs)
|
||||
(+ xs))
|
||||
|
||||
;; TODO: Call F on A followed by the elements of XS, using APPLY.
|
||||
(defun call-with-more (f a xs)
|
||||
(funcall f a))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 6 (sum-of '(1 2 3)))
|
||||
(check-equal 0 (sum-of '()))
|
||||
(check-equal 10 (call-with-more #'+ 1 '(2 3 4)))
|
||||
(check-equal 5 (call-with-more #'max 1 '(5 2)))
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; FUNCTIONAL 4: REDUCE
|
||||
;;;
|
||||
;;; REDUCE folds a list to a single value:
|
||||
;;; (reduce #'+ '(1 2 3)) => 6
|
||||
;;; (reduce #'max '(3 1 4)) => 4
|
||||
|
||||
;; TODO: The biggest number in XS, with REDUCE.
|
||||
(defun biggest (xs)
|
||||
(reduce #'+ xs))
|
||||
|
||||
;; TODO: The product of XS; an empty list multiplies to 1.
|
||||
(defun product (xs)
|
||||
(reduce #'+ xs :initial-value 0))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 4 (biggest '(3 1 4)))
|
||||
(check-equal 2 (biggest '(2)))
|
||||
(check-equal 6 (product '(1 2 3)))
|
||||
(check-equal 7 (product '(7)))
|
||||
(check-equal 1 (product '()))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 09_strings
|
||||
|
||||
FORMAT directives, the string toolbox, joining and comparing.
|
||||
|
||||
FORMAT is a mini-language of directives: ~a prints, ~{...~} iterates.
|
||||
STRING-EQUAL compares ignoring case.
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; STRINGS 1: FORMAT DIRECTIVES
|
||||
;;;
|
||||
;;; FORMAT is a little language: ~a prints readably, ~10a pads to a
|
||||
;;; width, ~% is a newline. The first argument NIL means "return a
|
||||
;;; string" instead of printing.
|
||||
;;; (format nil "Hello, ~a!" "Ada") => "Hello, Ada!"
|
||||
|
||||
;; TODO: "Ada has 42 cats." with the name and count in place.
|
||||
(defun cats (name count)
|
||||
(format nil "has cats."))
|
||||
|
||||
;; TODO: NAME left-justified in 10 columns, then an exclamation
|
||||
;;; mark.
|
||||
(defun banner (name)
|
||||
(format nil "Hello, ~a!" name))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "Ada has 42 cats." (cats "Ada" 42))
|
||||
(check-equal "Bob has 7 cats." (cats "Bob" 7))
|
||||
(check-equal "Ada !" (banner "Ada"))
|
||||
(check-equal "Grace !" (banner "Grace"))
|
||||
@@ -0,0 +1,28 @@
|
||||
;;; STRINGS 2: THE STRING TOOLBOX
|
||||
;;;
|
||||
;;; LENGTH counts characters. SUBSEQ slices: (subseq "hello" 1 3)
|
||||
;;; is "el". STRING-UPCASE shouts. SEARCH finds a substring and
|
||||
;;; returns its position - case-sensitively.
|
||||
|
||||
;; TODO: The first three characters of S.
|
||||
(defun first-three (s)
|
||||
(subseq s 1 3))
|
||||
|
||||
;; TODO: S uppercased with "!!" on the end.
|
||||
(defun shout (s)
|
||||
(string-downcase s))
|
||||
|
||||
;; TODO: The position of "lisp" inside S, or NIL.
|
||||
(defun find-lisp (s)
|
||||
(search "LISP" s))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "hel" (first-three "hello"))
|
||||
(check-equal "ADA!!" (shout "ada"))
|
||||
(check-equal "GRACE!!" (shout "grace"))
|
||||
(check-equal 2 (find-lisp "i lisp things"))
|
||||
(check-equal nil (find-lisp "not here"))
|
||||
@@ -0,0 +1,23 @@
|
||||
;;; STRINGS 3: JOINING AND COMPARING
|
||||
;;;
|
||||
;;; CONCATENATE joins strings: (concatenate 'string "a" "b") =>
|
||||
;;; "ab". STRING= is exact; STRING-EQUAL ignores case.
|
||||
;;; Comparing strings with EQ is unreliable: strings are objects.
|
||||
|
||||
;; TODO: FIRST and LAST joined with one space between.
|
||||
(defun full-name (first last)
|
||||
(list first last))
|
||||
|
||||
;; TODO: T when FIRST and LAST are the same name, ignoring case.
|
||||
(defun same-name-p (first last)
|
||||
(eq first last))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "Ada Lovelace" (full-name "Ada" "Lovelace"))
|
||||
(check-equal "Alan Turing" (full-name "Alan" "Turing"))
|
||||
(check (same-name-p "Ada" "ADA"))
|
||||
(check (not (same-name-p "Ada" "Grace")))
|
||||
@@ -0,0 +1,23 @@
|
||||
;;; STRINGS 4: FORMAT ITERATION
|
||||
;;;
|
||||
;;; ~{ ... ~} walks a list argument, and ~^ skips what follows at
|
||||
;;; the last element:
|
||||
;;; (format nil "~{~a~^, ~}" '(1 2 3)) => "1, 2, 3"
|
||||
|
||||
;; TODO: The numbers joined with ", ".
|
||||
(defun comma-list (xs)
|
||||
(format nil "~a" xs))
|
||||
|
||||
;; TODO: The names, one per line, with no trailing newline.
|
||||
(defun lines (names)
|
||||
(format nil "~a" names))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "1, 2, 3" (comma-list '(1 2 3)))
|
||||
(check-equal "" (comma-list '()))
|
||||
(check-equal "ada
|
||||
grace" (lines '("ada" "grace")))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 10_loops
|
||||
|
||||
DOLIST, DOTIMES, and the LOOP macro.
|
||||
|
||||
DOLIST and DOTIMES are simple walkers. LOOP is a composable
|
||||
sublanguage: FOR ... COLLECT, SUM, WHEN, THEREIS.
|
||||
@@ -0,0 +1,30 @@
|
||||
;;; LOOPS 1: DOLIST AND DOTIMES
|
||||
;;;
|
||||
;;; (dolist (x xs) body) walks a list.
|
||||
;;; (dotimes (i n) body) counts from 0 to n-1.
|
||||
;;; Both accept an optional result form: (dolist (x xs result) ...).
|
||||
|
||||
;; TODO: The sum of XS, one element at a time.
|
||||
(defun sum-of (xs)
|
||||
(let ((total 0))
|
||||
(dolist (x xs)
|
||||
total)
|
||||
total))
|
||||
|
||||
;; TODO: The countdown (2 1 0) for N=3. DOTIMES counts up, so PUSH
|
||||
;;; each I and the order flips for free.
|
||||
(defun countdown (n)
|
||||
(let ((acc '()))
|
||||
(dotimes (i n)
|
||||
acc)
|
||||
acc))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 6 (sum-of '(1 2 3)))
|
||||
(check-equal 0 (sum-of '()))
|
||||
(check-equal '(2 1 0) (countdown 3))
|
||||
(check-equal '() (countdown 0))
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; LOOPS 2: THE LOOP MACRO
|
||||
;;;
|
||||
;;; LOOP is a whole sublanguage:
|
||||
;;; (loop for x in '(1 2 3) collect (* x x)) => (1 4 9)
|
||||
;;; (loop for i from 1 to 10 sum i) => 55
|
||||
|
||||
;; TODO: The squares of XS, with LOOP ... COLLECT.
|
||||
(defun squares (xs)
|
||||
(loop for x in xs
|
||||
collect x))
|
||||
|
||||
;; TODO: The sum 1 + 2 + ... + N, with LOOP ... SUM.
|
||||
(defun triangle (n)
|
||||
(loop for i from 1 to n
|
||||
collect i))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(1 4 9) (squares '(1 2 3)))
|
||||
(check-equal 6 (triangle 3))
|
||||
(check-equal 55 (triangle 10))
|
||||
(check-equal 0 (triangle 0))
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; LOOPS 3: LOOP WITH TESTS
|
||||
;;;
|
||||
;;; LOOP clauses compose: WHEN filters, THEREIS stops at the first
|
||||
;;; non-NIL value and returns it.
|
||||
;;; (loop for x in xs when (evenp x) collect x)
|
||||
|
||||
;; TODO: Only the even numbers of XS, with LOOP and WHEN.
|
||||
(defun evens (xs)
|
||||
(loop for x in xs
|
||||
collect x))
|
||||
|
||||
;; TODO: The first number in XS over 100, or NIL, with THEREIS.
|
||||
(defun first-big (xs)
|
||||
(loop for x in xs
|
||||
collect x))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(2 4 6) (evens '(1 2 3 4 5 6)))
|
||||
(check-equal '() (evens '(1 3)))
|
||||
(check-equal 150 (first-big '(5 150 250 3)))
|
||||
(check-equal nil (first-big '(1 2 3)))
|
||||
@@ -0,0 +1,6 @@
|
||||
# 11_numbers
|
||||
|
||||
The number tower: integers, rationals, floats.
|
||||
|
||||
Integers grow without limit and (/ 7 2) is the exact rational 7/2.
|
||||
FLOOR, MOD and friends round and divide with exact rules.
|
||||
@@ -0,0 +1,21 @@
|
||||
;;; NUMBERS 1: THE TOWER
|
||||
;;;
|
||||
;;; Integers grow forever: (expt 2 100) is exact.
|
||||
;;; (/ 7 2) is the rational 7/2 - exact, not 3.
|
||||
;;; A float anywhere drags the result into floating point.
|
||||
|
||||
;; TODO: The exact value of 2^100.
|
||||
(defun two-to-the-hundred ()
|
||||
(expt 2.0 100))
|
||||
|
||||
;; TODO: Half of 7, exactly, as a ratio.
|
||||
(defun half-of-seven ()
|
||||
(/ 7 2.0))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 1267650600228229401496703205376 (two-to-the-hundred))
|
||||
(check-equal 7/2 (half-of-seven))
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; NUMBERS 2: ROUNDING AND REMAINDERS
|
||||
;;;
|
||||
;;; FLOOR rounds toward minus infinity, CEILING up, TRUNCATE toward
|
||||
;;; zero. MOD follows FLOOR's sign; REM follows TRUNCATE's.
|
||||
;;; (mod -7 2) => 1 (rem -7 2) => -1
|
||||
|
||||
;; TODO: Round X down to a multiple of 5.
|
||||
(defun floor-to-five (x)
|
||||
(* 5 (ceiling x 5)))
|
||||
|
||||
;; TODO: The remainder of X divided by 5, always in 0..4.
|
||||
(defun mod-five (x)
|
||||
(rem x 5))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 10 (floor-to-five 12))
|
||||
(check-equal 10 (floor-to-five 14))
|
||||
(check-equal 15 (floor-to-five 15))
|
||||
(check-equal 4 (mod-five 9))
|
||||
(check-equal 0 (mod-five -5))
|
||||
(check-equal 1 (mod-five -9))
|
||||
@@ -0,0 +1,32 @@
|
||||
;;; NUMBERS 3: BOUNDS AND STEPS
|
||||
;;;
|
||||
;;; MIN and MAX bound a value; ABS takes the size; INCF and DECF
|
||||
;;; step a variable (or any place) up and down.
|
||||
|
||||
;; TODO: Clamp X into the range LOW..HIGH.
|
||||
(defun clamp (x low high)
|
||||
(max low x))
|
||||
|
||||
;; TODO: The absolute distance between A and B.
|
||||
(defun distance-1d (a b)
|
||||
(- a b))
|
||||
|
||||
;; TODO: Start at 10; step up by 1, down by 2, up by 5. Return the
|
||||
;;; number you end on.
|
||||
(defun walk ()
|
||||
(let ((n 10))
|
||||
(incf n)
|
||||
n))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 5 (clamp 12 0 5))
|
||||
(check-equal 0 (clamp -3 0 5))
|
||||
(check-equal 3 (clamp 3 0 5))
|
||||
(check-equal 3 (distance-1d 5 2))
|
||||
(check-equal 3 (distance-1d 2 5))
|
||||
(check-equal 0 (distance-1d 4 4))
|
||||
(check-equal 14 (walk))
|
||||
@@ -0,0 +1,5 @@
|
||||
# 12_structs
|
||||
|
||||
DEFSTRUCT: constructors, readers, predicates, defaults, inheritance.
|
||||
|
||||
One form generates a whole toolkit around a record type.
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; STRUCTS 1: DEFSTRUCT
|
||||
;;;
|
||||
;;; DEFSTRUCT defines a record type and generates, for free:
|
||||
;;; a constructor (make-person), slot readers (person-name),
|
||||
;;; and a predicate (personp).
|
||||
|
||||
(defstruct person
|
||||
name
|
||||
age)
|
||||
|
||||
;; TODO: Make Ada: name "Ada", age 36.
|
||||
(defun make-ada ()
|
||||
(make-person :name "Ada"))
|
||||
|
||||
;; TODO: Ada's age.
|
||||
(defun ada-age (ada)
|
||||
(person-name ada))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((ada (make-ada)))
|
||||
(and (equal "Ada" (person-name ada))
|
||||
(eql 36 (person-age ada)))))
|
||||
(check (eql 36 (ada-age (make-ada))))
|
||||
@@ -0,0 +1,29 @@
|
||||
;;; STRUCTS 2: DEFAULTS AND PREDICATES
|
||||
;;;
|
||||
;;; Slots may have defaults: (name "unnamed"). DEFSTRUCT also
|
||||
;;; generates a type predicate: spaceship-p.
|
||||
|
||||
(defstruct spaceship
|
||||
(name "unnamed")
|
||||
(crew-size 1))
|
||||
|
||||
;; TODO: A ship with the default name and a crew of 7.
|
||||
(defun seven-crew ()
|
||||
(make-spaceship :crew-size 1))
|
||||
|
||||
;; TODO: T when X is a spaceship, NIL otherwise. The predicate was
|
||||
;;; generated for you.
|
||||
(defun ship-p (x)
|
||||
t)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((s (seven-crew)))
|
||||
(and (equal "unnamed" (spaceship-name s))
|
||||
(eql 7 (spaceship-crew-size s)))))
|
||||
(check (and (ship-p (make-spaceship))
|
||||
(not (ship-p "a plain string"))
|
||||
(not (ship-p 42))))
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; STRUCTS 3: MUTATION
|
||||
;;;
|
||||
;;; Struct slots are SETF places:
|
||||
;;; (setf (person-age p) 37)
|
||||
|
||||
(defstruct counter
|
||||
(value 0))
|
||||
|
||||
;; TODO: Add ONE to the counter's value. Return the counter.
|
||||
(defun bump (c)
|
||||
c)
|
||||
|
||||
;; TODO: Set the counter back to zero. Return the counter.
|
||||
(defun reset-counter (c)
|
||||
c)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((c (make-counter)))
|
||||
(bump c)
|
||||
(eql 1 (counter-value c))))
|
||||
(check (let ((c (make-counter :value 9)))
|
||||
(reset-counter c)
|
||||
(eql 0 (counter-value c))))
|
||||
@@ -0,0 +1,29 @@
|
||||
;;; STRUCTS 4: INHERITANCE
|
||||
;;;
|
||||
;;; :INCLUDE extends a struct. A student IS a person, with every
|
||||
;;; person slot, plus a major.
|
||||
|
||||
(defstruct person
|
||||
name
|
||||
age)
|
||||
|
||||
(defstruct (student (:include person))
|
||||
major)
|
||||
|
||||
;; TODO: Make Zed: name "Zed", age 21, studying physics.
|
||||
(defun make-zed ()
|
||||
(make-person :name "Zed"))
|
||||
|
||||
;; TODO: Zed's major.
|
||||
(defun zed-major (zed)
|
||||
(person-name zed))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((zed (make-zed)))
|
||||
(and (equal "Zed" (student-name zed))
|
||||
(eql 21 (student-age zed))
|
||||
(equal "physics" (zed-major zed)))))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 13_hash_tables
|
||||
|
||||
MAKE-HASH-TABLE, GETHASH, presence, and counting.
|
||||
|
||||
GETHASH returns two values: the stored value, and whether the key
|
||||
exists at all. That second value is the honest answer to "is it
|
||||
there?"
|
||||
@@ -0,0 +1,23 @@
|
||||
;;; HASH TABLES 1: BASICS
|
||||
;;;
|
||||
;;; (make-hash-table) creates one; (gethash key table) looks a key
|
||||
;;; up; (setf (gethash key table) value) stores one.
|
||||
|
||||
;; TODO: A table mapping ada to 36 and grace to 45.
|
||||
(defun people ()
|
||||
(let ((table (make-hash-table)))
|
||||
table))
|
||||
|
||||
;; TODO: The age stored for NAME in TABLE, or NIL when absent.
|
||||
(defun age-of (name table)
|
||||
(gethash name))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((table (people)))
|
||||
(and (eql 36 (age-of 'ada table))
|
||||
(eql 45 (age-of 'grace table))
|
||||
(eq nil (age-of 'alan table)))))
|
||||
@@ -0,0 +1,30 @@
|
||||
;;; HASH TABLES 2: IS THE KEY THERE?
|
||||
;;;
|
||||
;;; GETHASH returns TWO values: the stored value, and T or NIL for
|
||||
;;; presence. A stored NIL is different from an absent key!
|
||||
;;; (multiple-value-bind (value present) (gethash key table) ...)
|
||||
|
||||
;; TODO: T when KEY exists in TABLE (even with a NIL value), NIL
|
||||
;;; otherwise.
|
||||
(defun has-key-p (key table)
|
||||
(gethash key table))
|
||||
|
||||
;; TODO: The value for KEY, or DEFAULT when the key is absent.
|
||||
(defun lookup (key table default)
|
||||
(gethash key table))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((table (make-hash-table)))
|
||||
(setf (gethash 'a table) 1
|
||||
(gethash 'b table) nil)
|
||||
(and (has-key-p 'a table)
|
||||
(has-key-p 'b table)
|
||||
(not (has-key-p 'c table)))))
|
||||
(check (let ((table (make-hash-table)))
|
||||
(setf (gethash 'a table) 1)
|
||||
(and (eql 1 (lookup 'a table 0))
|
||||
(eql 99 (lookup 'c table 99)))))
|
||||
@@ -0,0 +1,22 @@
|
||||
;;; HASH TABLES 3: COUNTING
|
||||
;;;
|
||||
;;; The classic hash-table job: tally. GETHASH takes a default:
|
||||
;;; (gethash x table 0)
|
||||
;;; so a missing key counts as 0 and INCF can do the rest.
|
||||
|
||||
;; TODO: Count the occurrences of each element of XS. Return the
|
||||
;;; table.
|
||||
(defun tally (xs)
|
||||
(let ((table (make-hash-table)))
|
||||
table))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((table (tally '(a b a c a b))))
|
||||
(and (eql 3 (gethash 'a table))
|
||||
(eql 2 (gethash 'b table))
|
||||
(eql 1 (gethash 'c table))
|
||||
(eql 3 (hash-table-count table)))))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 14_packages
|
||||
|
||||
DEFPACKAGE, IN-PACKAGE, exports, and :USE.
|
||||
|
||||
A package is a namespace. Only exported symbols are visible through
|
||||
a single colon; :USE imports them all, the way CL-USER uses
|
||||
COMMON-LISP.
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; PACKAGES 1: DEFPACKAGE
|
||||
;;;
|
||||
;;; A package is a namespace of symbols. DEFPACKAGE defines one,
|
||||
;;; IN-PACKAGE switches to it, and :EXPORT lists the names the
|
||||
;;; outside world may see.
|
||||
|
||||
(defpackage #:shapes
|
||||
(:use #:common-lisp)
|
||||
(:export #:area))
|
||||
|
||||
(in-package #:shapes)
|
||||
|
||||
;; TODO: Return the area of a square with side S.
|
||||
(defun area (s)
|
||||
0)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged. (Checks run back in the user package.)
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(in-package #:common-lisp-user)
|
||||
|
||||
(check-equal 25 (shapes:area 5))
|
||||
(check-equal 9 (shapes:area 3))
|
||||
@@ -0,0 +1,21 @@
|
||||
;;; PACKAGES 2: EXPORTS
|
||||
;;;
|
||||
;;; A single colon reaches only EXPORTED symbols. The kitchen
|
||||
;;; makes soup; only the soup is on the menu.
|
||||
|
||||
(defpackage #:kitchen
|
||||
(:use #:common-lisp))
|
||||
|
||||
(in-package #:kitchen)
|
||||
|
||||
(defun make-soup ()
|
||||
"a pot of soup")
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged. (Checks run back in the user package.)
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(in-package #:common-lisp-user)
|
||||
|
||||
(check-equal "a pot of soup" (kitchen:make-soup))
|
||||
@@ -0,0 +1,34 @@
|
||||
;;; PACKAGES 3: USING ANOTHER PACKAGE
|
||||
;;;
|
||||
;;; (:use ...) imports every EXPORTED symbol of a package, the way
|
||||
;;; CL-USER uses COMMON-LISP. The studio uses SHAPES, so AREA is
|
||||
;;; simply there.
|
||||
|
||||
(defpackage #:shapes
|
||||
(:use #:common-lisp)
|
||||
(:export #:area))
|
||||
|
||||
(in-package #:shapes)
|
||||
|
||||
(defun area (s)
|
||||
(* s s))
|
||||
|
||||
(defpackage #:studio
|
||||
(:use #:common-lisp #:shapes)
|
||||
(:export #:total))
|
||||
|
||||
(in-package #:studio)
|
||||
|
||||
;; TODO: The combined area of two squares with sides A and B.
|
||||
(defun total (a b)
|
||||
area)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged. (Checks run back in the user package.)
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(in-package #:common-lisp-user)
|
||||
|
||||
(check-equal 13 (studio:total 2 3))
|
||||
(check-equal 5 (studio:total 1 2))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 15_clos
|
||||
|
||||
Classes, instances, generic dispatch, and method combination.
|
||||
|
||||
DEFGENERIC names an operation; DEFMETHOD implements it, once per
|
||||
class. :BEFORE and :AFTER methods combine around the primary one,
|
||||
and (EQL x) specializers dispatch on a single value.
|
||||
@@ -0,0 +1,22 @@
|
||||
;;; CLOS 1: CLASSES AND INSTANCES
|
||||
;;;
|
||||
;;; DEFCLASS defines a class; slots take :INITARG keywords to fill
|
||||
;;; them and :ACCESSOR names to read them.
|
||||
;;; (make-instance 'dog :name "Rex")
|
||||
|
||||
(defclass dog ()
|
||||
((name :initarg :name :accessor dog-name)
|
||||
(tricks :initarg :tricks :accessor dog-tricks :initform '())))
|
||||
|
||||
;; TODO: A dog named "Rex" who knows "sit" and "roll-over".
|
||||
(defun make-rex ()
|
||||
nil)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((rex (make-rex)))
|
||||
(and (string= "Rex" (dog-name rex))
|
||||
(equal '("sit" "roll-over") (dog-tricks rex)))))
|
||||
@@ -0,0 +1,27 @@
|
||||
;;; CLOS 2: GENERIC FUNCTIONS
|
||||
;;;
|
||||
;;; DEFGENERIC names an operation; DEFMETHOD implements it, once
|
||||
;;; per class. The class of each argument picks the method that
|
||||
;;; runs.
|
||||
|
||||
(defclass animal () ())
|
||||
(defclass dog (animal) ())
|
||||
(defclass cat (animal) ())
|
||||
|
||||
(defgeneric speak (a))
|
||||
|
||||
(defmethod speak ((a dog)) "woof")
|
||||
(defmethod speak ((a cat)) "meow")
|
||||
|
||||
;; TODO: Any other animal says "...".
|
||||
(defmethod speak ((a animal))
|
||||
"grrr")
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "woof" (speak (make-instance 'dog)))
|
||||
(check-equal "meow" (speak (make-instance 'cat)))
|
||||
(check-equal "..." (speak (make-instance 'animal)))
|
||||
@@ -0,0 +1,31 @@
|
||||
;;; CLOS 3: COMBINING METHODS
|
||||
;;;
|
||||
;;; :BEFORE runs first, the primary method runs, :AFTER runs last.
|
||||
;;; Every applicable method takes its turn.
|
||||
|
||||
(defclass account ()
|
||||
((log :initform '() :accessor account-log)
|
||||
(balance :initform 0 :accessor account-balance)))
|
||||
|
||||
(defgeneric deposit (account amount))
|
||||
|
||||
(defmethod deposit ((a account) amount)
|
||||
(incf (account-balance a) amount))
|
||||
|
||||
(defmethod deposit :before ((a account) amount)
|
||||
(push (list 'depositing amount) (account-log a)))
|
||||
|
||||
;; TODO: An :AFTER method that logs (list 'deposited amount).
|
||||
(defmethod deposit :after ((a account) amount)
|
||||
(account-log a))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((a (make-instance 'account)))
|
||||
(deposit a 50)
|
||||
(and (eql 50 (account-balance a))
|
||||
(equal '((deposited 50) (depositing 50))
|
||||
(account-log a)))))
|
||||
@@ -0,0 +1,22 @@
|
||||
;;; CLOS 4: DISPATCH ON A VALUE
|
||||
;;;
|
||||
;;; An (EQL x) specializer picks a method for one specific value.
|
||||
;;; It works for numbers, characters and symbols - values that are
|
||||
;;; their own identity.
|
||||
|
||||
(defgeneric serve (customer))
|
||||
|
||||
(defmethod serve (customer)
|
||||
"one espresso")
|
||||
|
||||
;; TODO: The customer 'vip gets a muffin too.
|
||||
(defmethod serve ((customer (eql 'vip)))
|
||||
"espresso")
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "a free muffin too" (serve 'vip))
|
||||
(check-equal "one espresso" (serve 'ada))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 16_conditions
|
||||
|
||||
Conditions, handlers, restarts: the crown jewel of Common Lisp.
|
||||
|
||||
ERROR signals, HANDLER-CASE catches, UNWIND-PROTECT cleans up.
|
||||
DEFINE-CONDITION makes your own error types, and restarts let the
|
||||
recovery happen exactly where it makes sense.
|
||||
@@ -0,0 +1,22 @@
|
||||
;;; CONDITIONS 1: ERROR AND HANDLER-CASE
|
||||
;;;
|
||||
;;; ERROR signals a condition; HANDLER-CASE catches it, by type:
|
||||
;;; (handler-case (error "boom")
|
||||
;;; (error (e) :caught))
|
||||
;;;
|
||||
;;; That is the Lisp try/catch, with one twist: conditions are
|
||||
;;; CLASSES, so the catch is a type test.
|
||||
|
||||
;; TODO: Parse STRING with PARSE-INTEGER; when it does not parse,
|
||||
;;; return :not-a-number instead of crashing.
|
||||
(defun safe-parse (string)
|
||||
(parse-integer string))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 42 (safe-parse "42"))
|
||||
(check-equal -7 (safe-parse "-7"))
|
||||
(check-equal :not-a-number (safe-parse "hello"))
|
||||
@@ -0,0 +1,25 @@
|
||||
;;; CONDITIONS 2: UNWIND-PROTECT
|
||||
;;;
|
||||
;;; When an error unwinds the stack, UNWIND-PROTECT guarantees the
|
||||
;;; cleanup form still runs: the Lisp try/finally.
|
||||
|
||||
(defparameter *lid* :closed)
|
||||
|
||||
;; TODO: Call F with the lid :open, and ALWAYS set it back to
|
||||
;;; :closed afterwards - even when F signals an error.
|
||||
(defun with-lid (f)
|
||||
(setf *lid* :open)
|
||||
(funcall f))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (progn (with-lid (lambda () 1))
|
||||
(eq :closed *lid*)))
|
||||
(check (handler-case
|
||||
(progn (with-lid (lambda () (error "oops")))
|
||||
nil)
|
||||
(error () t)))
|
||||
(check (eq :closed *lid*))
|
||||
@@ -0,0 +1,26 @@
|
||||
;;; CONDITIONS 3: YOUR OWN CONDITION TYPES
|
||||
;;;
|
||||
;;; Conditions are classes. DEFINE-CONDITION defines new ones with
|
||||
;;; :INITARGs; ERROR signals them; HANDLER-CASE catches by type.
|
||||
|
||||
(define-condition empty-plate (error)
|
||||
((what :initarg :what :reader empty-plate-what))
|
||||
(:documentation "Signaled when a plate turns out to be empty."))
|
||||
|
||||
;; TODO: eat returns "yum" - unless XS is NIL, when it signals
|
||||
;;; empty-plate with :what "soup".
|
||||
(defun eat (xs)
|
||||
"yum")
|
||||
|
||||
;; TODO: catch-empty calls (eat xs); when the plate is empty it
|
||||
;;; returns the condition's WHAT instead.
|
||||
(defun catch-empty (xs)
|
||||
(eat xs))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal "yum" (catch-empty '(a b)))
|
||||
(check-equal "soup" (catch-empty '()))
|
||||
@@ -0,0 +1,33 @@
|
||||
;;; CONDITIONS 4: RESTARTS
|
||||
;;;
|
||||
;;; The crown jewel. A RESTART is a named escape hatch established
|
||||
;;; where the error happens; the handler, far above, chooses one by
|
||||
;;; name. The signaling code offers choices; the handling code
|
||||
;;; decides.
|
||||
;;;
|
||||
;;; (restart-case (error "bad")
|
||||
;;; (use-nil () nil))
|
||||
;;;
|
||||
;;; (handler-bind ((error (lambda (e)
|
||||
;;; (declare (ignore e))
|
||||
;;; (invoke-restart 'use-nil))))
|
||||
;;; (something-that-errors))
|
||||
|
||||
;; TODO: safe-car signals an error for anything that is not a CONS,
|
||||
;;; but offers a USE-NIL restart that returns NIL instead.
|
||||
(defun safe-car (xs)
|
||||
(car xs))
|
||||
|
||||
;; TODO: car-with-default calls SAFE-CAR; on any error it invokes
|
||||
;;; the USE-NIL restart, so the result is NIL rather than a crash.
|
||||
(defun car-with-default (xs)
|
||||
(safe-car xs))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 1 (car-with-default '(1 2 3)))
|
||||
(check-equal nil (car-with-default "not a list"))
|
||||
(check-equal nil (car-with-default nil))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 17_macros
|
||||
|
||||
DEFMACRO, backquote templates, hygiene with GENSYM.
|
||||
|
||||
A macro writes code. The backquote family (` , ,@) makes templates
|
||||
cheap, and GENSYM keeps a macro's own variables from capturing
|
||||
yours.
|
||||
@@ -0,0 +1,19 @@
|
||||
;;; MACROS 1: DEFMACRO
|
||||
;;;
|
||||
;;; A macro takes unevaluated CODE and returns the code to run.
|
||||
;;; DEFMACRO defines one; the arguments arrive as source, not
|
||||
;;; values.
|
||||
|
||||
;; TODO: my-when expands (my-when test body...) so the body runs
|
||||
;;; only when TEST is true; the whole form is NIL otherwise.
|
||||
(defmacro my-when (test &body body)
|
||||
`(progn ,test ,@body))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 5 (my-when t 5))
|
||||
(check-equal nil (my-when nil 5))
|
||||
(check-equal :more (my-when t :ok :more))
|
||||
@@ -0,0 +1,24 @@
|
||||
;;; MACROS 2: BACKQUOTE, COMMA, SPLICE
|
||||
;;;
|
||||
;;; ` is a code template. Inside it almost everything is literal,
|
||||
;;; except:
|
||||
;;; ,expr inserts the value of expr
|
||||
;;; ,@expr SPLICES a list into the surrounding list
|
||||
|
||||
;; TODO: (boxed <x>): the symbol BOXED with the VALUE of X inside.
|
||||
(defun wrap-value (x)
|
||||
`(boxed x))
|
||||
|
||||
;; TODO: (add <numbers...>): the symbol ADD with the numbers
|
||||
;;; spliced in.
|
||||
(defun make-add-form (numbers)
|
||||
`(add))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal '(boxed 42) (wrap-value 42))
|
||||
(check-equal '(add 2 3 4) (make-add-form '(2 3 4)))
|
||||
(check-equal '(add) (make-add-form '()))
|
||||
@@ -0,0 +1,21 @@
|
||||
;;; MACROS 3: GENSYM AND HYGIENE
|
||||
;;;
|
||||
;;; A macro that introduces its own variables can capture the
|
||||
;;; user's variables by accident. GENSYM makes a name that cannot
|
||||
;;; collide, because it never existed before.
|
||||
|
||||
;; TODO: n-plus-five should add 5 to the user's N. The macro's own
|
||||
;;; temp variable must not shadow it - use GENSYM.
|
||||
(defmacro n-plus-five (n)
|
||||
`(let ((n 5))
|
||||
(+ n ,n)))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 7 (let ((n 2))
|
||||
(n-plus-five n)))
|
||||
(check-equal 15 (let ((n 10))
|
||||
(n-plus-five n)))
|
||||
@@ -0,0 +1,28 @@
|
||||
;;; MACROS 4: A MACRO OF YOUR OWN
|
||||
;;;
|
||||
;;; MACROEXPAND-1 shows what any macro does with your code - try it
|
||||
;;; in a REPL. Time to write a real one: WHILE runs its body until
|
||||
;;; the test turns NIL.
|
||||
;;;
|
||||
;;; (let ((i 0))
|
||||
;;; (while (< i 3)
|
||||
;;; (incf i))
|
||||
;;; i) => 3
|
||||
|
||||
;; TODO: Define while with LOOP.
|
||||
(defmacro while (test &body body)
|
||||
`(progn ,test))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 3 (let ((i 0))
|
||||
(while (< i 3)
|
||||
(incf i))
|
||||
i))
|
||||
(check-equal '() (let ((acc '()))
|
||||
(while nil
|
||||
(push 1 acc))
|
||||
acc))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 18_dynamic
|
||||
|
||||
Closures and special variables: two ways a function reaches out.
|
||||
|
||||
A closure captures the variables around it. A DEFPARAMETER variable
|
||||
is dynamic: LET rebinding it changes what every called function
|
||||
sees, and restores the old value afterwards.
|
||||
@@ -0,0 +1,21 @@
|
||||
;;; DYNAMIC 1: CLOSURES
|
||||
;;;
|
||||
;;; A LAMBDA captures the variables around it - the variable
|
||||
;;; itself, not its value. The closure sees every change, and its
|
||||
;;; own changes persist between calls.
|
||||
|
||||
;; TODO: A counter closure: it starts at 0; every call returns the
|
||||
;;; NEW count (1, 2, 3, ...).
|
||||
(defun make-counter ()
|
||||
(let ((count 0))
|
||||
(lambda () count)))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((c1 (make-counter))
|
||||
(c2 (make-counter)))
|
||||
(and (equal '(1 2 3) (list (funcall c1) (funcall c1) (funcall c1)))
|
||||
(eql 1 (funcall c2)))))
|
||||
@@ -0,0 +1,26 @@
|
||||
;;; DYNAMIC 2: SPECIAL VARIABLES
|
||||
;;;
|
||||
;;; DEFPARAMETER makes a SPECIAL variable. LET rebinding it
|
||||
;;; changes what EVERYONE sees during the LET - including the
|
||||
;;; functions you call. The old value comes back automatically.
|
||||
|
||||
(defparameter *depth* 0)
|
||||
|
||||
(defun current-depth ()
|
||||
*depth*)
|
||||
|
||||
;; TODO: Call F while *depth* is bound to N - and have the old
|
||||
;;; value restored afterwards.
|
||||
(defun with-depth (n f)
|
||||
(setf *depth* n)
|
||||
(funcall f))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (eql 7 (with-depth 7 (lambda () (current-depth)))))
|
||||
(check (eql 0 (current-depth)))
|
||||
(check (eql 3 (let ((*depth* 3)) (current-depth))))
|
||||
(check (eql 0 (current-depth)))
|
||||
@@ -0,0 +1,32 @@
|
||||
;;; DYNAMIC 3: A MEMOIZING CLOSURE
|
||||
;;;
|
||||
;;; Closures plus hash tables: remember what you computed. The
|
||||
;;; counter below watches how many times the slow function really
|
||||
;;; runs; a memoized second call must not run it again.
|
||||
|
||||
(defparameter *fib-calls* 0)
|
||||
|
||||
(defun slow-fib (n)
|
||||
(incf *fib-calls*)
|
||||
(if (< n 2)
|
||||
n
|
||||
(+ (slow-fib (- n 1)) (slow-fib (- n 2)))))
|
||||
|
||||
;; TODO: A closure over a hash table: when N is already in the
|
||||
;;; table, return the stored answer; otherwise compute it with
|
||||
;;; SLOW-FIB, store it, and return it.
|
||||
(defun make-memo-fib ()
|
||||
(let ((table (make-hash-table)))
|
||||
(lambda (n) (slow-fib n))))
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (let ((fib (make-memo-fib)))
|
||||
(setf *fib-calls* 0)
|
||||
(and (eql 55 (funcall fib 10))
|
||||
(let ((after-first *fib-calls*))
|
||||
(and (eql 55 (funcall fib 10))
|
||||
(eql after-first *fib-calls*))))))
|
||||
@@ -0,0 +1,7 @@
|
||||
# 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
|
||||
arithmetic s-expressions, written in the language it evaluates.
|
||||
@@ -0,0 +1,41 @@
|
||||
;;; QUIZ 1: THE CONTACT BOOK
|
||||
;;;
|
||||
;;; Everything from the first chapters in one place: plists, lists,
|
||||
;;; strings, conditionals, and FORMAT.
|
||||
;;;
|
||||
;;; A contact is a property list:
|
||||
;;; (:name "Ada" :email "ada@example.com")
|
||||
;;; The book is a list of contacts.
|
||||
|
||||
(defparameter *book*
|
||||
(list (list :name "Ada" :email "ada@example.com")
|
||||
(list :name "Grace" :email "grace@example.com")))
|
||||
|
||||
;; TODO: The book with a new contact appended.
|
||||
(defun add-contact (book name email)
|
||||
book)
|
||||
|
||||
;; TODO: The first contact whose :name matches NAME (ignoring
|
||||
;;; case), or NIL.
|
||||
(defun find-contact (book name)
|
||||
nil)
|
||||
|
||||
;; TODO: "Ada <ada@example.com>" for a contact.
|
||||
(defun contact-card (contact)
|
||||
"")
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check (equal (list (list :name "Ada" :email "ada@example.com")
|
||||
(list :name "Grace" :email "grace@example.com")
|
||||
(list :name "Zed" :email "zed@example.com"))
|
||||
(add-contact *book* "Zed" "zed@example.com")))
|
||||
(check (equal '(:name "Zed" :email "zed@example.com")
|
||||
(find-contact (add-contact *book* "Zed" "zed@example.com")
|
||||
"zed")))
|
||||
(check-equal nil (find-contact *book* "nope"))
|
||||
(check-equal "Ada <ada@example.com>"
|
||||
(contact-card (find-contact *book* "ada")))
|
||||
@@ -0,0 +1,29 @@
|
||||
;;; QUIZ 2: A TINY LISP, IN LISP
|
||||
;;;
|
||||
;;; The capstone. You have every tool you need; now write an
|
||||
;;; evaluator for a small arithmetic language.
|
||||
;;;
|
||||
;;; a number evaluates to itself
|
||||
;;; (quote x) evaluates to x, unevaluated
|
||||
;;; (+ a b), (- a b), the operator applied to the
|
||||
;;; (* a b) EVALUATED arguments
|
||||
;;; anything else an error: "cannot evaluate"
|
||||
;;;
|
||||
;;; Yes, this is how a Lisp works. This is that moment.
|
||||
|
||||
;; TODO: eval-expr.
|
||||
(defun eval-expr (expr)
|
||||
expr)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||
;;; them unchanged.
|
||||
;;; ------------------------------------------------------------------
|
||||
|
||||
(check-equal 7 (eval-expr 7))
|
||||
(check-equal 3 (eval-expr '(+ 1 2)))
|
||||
(check-equal 12 (eval-expr '(* (+ 1 2) 4)))
|
||||
(check-equal '(a b c) (eval-expr '(quote (a b c))))
|
||||
(check-equal -1 (eval-expr '(- (* 2 3) (+ 1 (+ 2 4)))))
|
||||
(check-error (eval-expr 'foo))
|
||||
(check-error (eval-expr '(lambda (x) x)))
|
||||
Reference in new issue
Block a user