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
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# Lisplings runtime state (created on first run)
|
||||||
|
.lisplings-state.sexp
|
||||||
|
.lisplings-orig/
|
||||||
|
|
||||||
|
# The rustlings reference checkout this project was built beside
|
||||||
|
rustlings/
|
||||||
|
|
||||||
|
# Editor and build droppings
|
||||||
|
*.fasl
|
||||||
|
*~
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
# Lisplings
|
||||||
|
|
||||||
|
```text
|
||||||
|
/
|
||||||
|
/
|
||||||
|
/
|
||||||
|
/\
|
||||||
|
/ \
|
||||||
|
/ \
|
||||||
|
```
|
||||||
|
|
||||||
|
Small exercises to get you used to reading and writing
|
||||||
|
[Common Lisp](https://common-lisp.net) code - recommended in parallel
|
||||||
|
with a book like [Practical Common Lisp](http://www.gigamonkeys.com/book/).
|
||||||
|
|
||||||
|
Lisplings is what [Rustlings](https://github.com/rust-lang/rustlings) is
|
||||||
|
to Rust: a watcher runs the exercise you are on, you fix it in your
|
||||||
|
editor, and saving the file runs it again. Everything, including the
|
||||||
|
exercises, the checks, and lisplings itself, is plain Common Lisp.
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
You need [SBCL](http://www.sbcl.org). Any recent version works; no
|
||||||
|
libraries beyond it.
|
||||||
|
|
||||||
|
### Without nix
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone <your fork>
|
||||||
|
cd lisplings
|
||||||
|
./lisplings
|
||||||
|
```
|
||||||
|
|
||||||
|
### With nix
|
||||||
|
|
||||||
|
The flake provides a pinned SBCL, a dev shell, and the lisplings
|
||||||
|
runner. The nix store is read-only, so create your own writable
|
||||||
|
course directory first - the runner then operates on the directory
|
||||||
|
it is started from:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
nix run . -- init my-lisplings # copy the course out of the store
|
||||||
|
cd my-lisplings
|
||||||
|
nix run /path/to/lisplings # watch mode, on this directory
|
||||||
|
```
|
||||||
|
|
||||||
|
`nix develop` gives a shell with SBCL for working on lisplings itself.
|
||||||
|
|
||||||
|
## The workflow
|
||||||
|
|
||||||
|
1. Run `./lisplings` from the repository root (or your project copy).
|
||||||
|
2. Edit the exercise file shown in the terminal, in any editor.
|
||||||
|
3. Save. The exercise runs again and its checks print.
|
||||||
|
4. When everything passes, press `n` for the next exercise.
|
||||||
|
|
||||||
|
Keys in watch mode:
|
||||||
|
|
||||||
|
| key | action |
|
||||||
|
| --- | --------------------------------------- |
|
||||||
|
| n | move to the next pending exercise |
|
||||||
|
| h | show a hint |
|
||||||
|
| r | rerun the current exercise |
|
||||||
|
| l | list all exercises |
|
||||||
|
| q | save progress and quit |
|
||||||
|
|
||||||
|
Really stuck? `solutions/` mirrors `exercises/` with every exercise
|
||||||
|
solved.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./lisplings watch the current exercise (the default)
|
||||||
|
./lisplings run [name] run one exercise and print its output
|
||||||
|
./lisplings hint [name] show the hint for an exercise
|
||||||
|
./lisplings list [pending|done|all]
|
||||||
|
./lisplings reset <name> restore an exercise to its pristine state
|
||||||
|
./lisplings check-all run every exercise and resync progress
|
||||||
|
./lisplings init [dir] create a lisplings project in dir
|
||||||
|
./lisplings help show all commands
|
||||||
|
```
|
||||||
|
|
||||||
|
Progress lives in `.lisplings-state.sexp` - a plain s-expression you can
|
||||||
|
read and edit. `reset` restores from a pristine snapshot taken under
|
||||||
|
`.lisplings-orig/` the first time lisplings ran there, so start lisplings
|
||||||
|
before editing anything.
|
||||||
|
|
||||||
|
## How an exercise works
|
||||||
|
|
||||||
|
Every exercise is a plain file of Common Lisp with the broken part
|
||||||
|
marked TODO, and a checks section at the bottom:
|
||||||
|
|
||||||
|
```lisp
|
||||||
|
;; TODO: Return twice the argument.
|
||||||
|
(defun twice (x)
|
||||||
|
x)
|
||||||
|
|
||||||
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
||||||
|
;;; them unchanged.
|
||||||
|
|
||||||
|
(check-equal 10 (twice 5))
|
||||||
|
```
|
||||||
|
|
||||||
|
The checks are ordinary macros, defined in `src/harness.lisp`: `check`
|
||||||
|
asserts a non-NIL value, `check-equal` compares with EQUAL, and
|
||||||
|
`check-error` waits for a condition. Nothing is hidden - the tests
|
||||||
|
live in the same file you edit, which is the Lispy way.
|
||||||
|
|
||||||
|
## The course
|
||||||
|
|
||||||
|
70 exercises in 20 chapters, from first forms to restarts, macros,
|
||||||
|
and a tiny Lisp interpreter:
|
||||||
|
|
||||||
|
```text
|
||||||
|
00_intro 01_sexps 02_functions 03_variables
|
||||||
|
04_conditionals 05_predicates 06_lists 07_recursion
|
||||||
|
08_functional 09_strings 10_loops 11_numbers
|
||||||
|
12_structs 13_hash_tables 14_packages 15_clos
|
||||||
|
16_conditions 17_macros 18_dynamic quizzes
|
||||||
|
```
|
||||||
|
|
||||||
|
Each chapter directory has a README with a two-line summary of the
|
||||||
|
ideas, and every exercise has a hint (`h`) and a solved twin under
|
||||||
|
`solutions/`.
|
||||||
|
|
||||||
|
## Hacking on lisplings
|
||||||
|
|
||||||
|
Lisplings itself is a few hundred lines of SBCL with no dependencies:
|
||||||
|
the watcher (`src/main.lisp`, `src/core.lisp`), the check harness every
|
||||||
|
exercise runs under (`src/harness.lisp`), and the subprocess that
|
||||||
|
runs one exercise (`src/exercise-runner.lisp`).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
dev/verify.sh # every exercise fails when broken, passes when solved
|
||||||
|
```
|
||||||
|
|
||||||
|
To add an exercise: write the broken `exercises/<chapter>/<name>.lisp`
|
||||||
|
and the solved `solutions/<chapter>/<name>.lisp`, add a `(:name ...
|
||||||
|
:dir ... :hint ...)` entry to `info.sexp`, and run `dev/verify.sh`.
|
||||||
Executable
+43
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Verify every exercise: the broken version must fail, and the
|
||||||
|
# solution must pass. Run from anywhere; operates on the repo root.
|
||||||
|
set -u
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
export NO_COLOR=1
|
||||||
|
|
||||||
|
sbcl --noinform --no-sysinit --no-userinit --disable-debugger \
|
||||||
|
--eval '(with-open-file (in "info.sexp")
|
||||||
|
(let ((specs (second (assoc :exercises (read in)))))
|
||||||
|
(dolist (s specs)
|
||||||
|
(format t "~a ~a~%" (getf s :dir) (getf s :name)))))' \
|
||||||
|
--quit > "${TMPDIR:-/tmp}/lisplings-exercise-list.txt" 2>/dev/null
|
||||||
|
|
||||||
|
fail=0
|
||||||
|
total=0
|
||||||
|
while read -r dir name; do
|
||||||
|
total=$((total+1))
|
||||||
|
sbcl --script src/exercise-runner.lisp "exercises/$dir/$name.lisp" > /dev/null 2>&1
|
||||||
|
b=$?
|
||||||
|
sbcl --script src/exercise-runner.lisp "solutions/$dir/$name.lisp" > /dev/null 2>&1
|
||||||
|
s=$?
|
||||||
|
if cmp -s "exercises/$dir/$name.lisp" "solutions/$dir/$name.lisp"; then
|
||||||
|
if [ "$s" -eq 0 ]; then
|
||||||
|
echo "ok $dir/$name (read-only)"
|
||||||
|
else
|
||||||
|
echo "BAD $dir/$name: SOLUTION FAILS ($s)"
|
||||||
|
fail=1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
if [ "$b" -ne 0 ] && [ "$s" -eq 0 ]; then
|
||||||
|
echo "ok $dir/$name"
|
||||||
|
else
|
||||||
|
echo "BAD $dir/$name: broken=$b solution=$s"
|
||||||
|
fail=1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done < "${TMPDIR:-/tmp}/lisplings-exercise-list.txt"
|
||||||
|
|
||||||
|
echo "----"
|
||||||
|
echo "verified $total exercises"
|
||||||
|
[ $fail -eq 0 ] && echo "ALL EXERCISES VERIFIED" || echo "FAILURES PRESENT"
|
||||||
|
exit $fail
|
||||||
@@ -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)))
|
||||||
Generated
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1795234589,
|
||||||
|
"narHash": "sha256-f/VVvxf5RsQgWVhUtefoca5ktVg0DA2bnkMOcmSnozo=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
description = "Lisplings: small exercises to get you used to reading and writing Common Lisp code";
|
||||||
|
|
||||||
|
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs }:
|
||||||
|
let
|
||||||
|
systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
|
||||||
|
forAllSystems = f:
|
||||||
|
nixpkgs.lib.genAttrs systems
|
||||||
|
(system: f system nixpkgs.legacyPackages.${system});
|
||||||
|
|
||||||
|
# Copy the project without the rustlings reference checkout or
|
||||||
|
# any local progress state.
|
||||||
|
projectSource = nixpkgs.lib.cleanSourceWith {
|
||||||
|
src = ./.;
|
||||||
|
filter = path: type:
|
||||||
|
!builtins.elem (nixpkgs.lib.baseNameOf path)
|
||||||
|
[ "rustlings"
|
||||||
|
".lisplings-state.sexp"
|
||||||
|
".lisplings-orig"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
devShells = forAllSystems (_system: pkgs: {
|
||||||
|
default = pkgs.mkShell {
|
||||||
|
packages = [ pkgs.sbcl ];
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
packages = forAllSystems (_system: pkgs: {
|
||||||
|
default = pkgs.callPackage ./nix/package.nix {
|
||||||
|
src = projectSource;
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
apps = forAllSystems (system: _pkgs: {
|
||||||
|
default = {
|
||||||
|
type = "app";
|
||||||
|
program = "${self.packages.${system}.default}/bin/lisplings";
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
;;; Lisplings exercise catalogue.
|
||||||
|
;;;
|
||||||
|
;;; Read by the lisplings runner. Each exercise is a plist:
|
||||||
|
;;; :name the exercise name; file is exercises/<dir>/<name>.lisp
|
||||||
|
;;; :dir the chapter directory
|
||||||
|
;;; :hint shown by `lisplings hint <name>'
|
||||||
|
|
||||||
|
((:welcome "Welcome to Lisplings!
|
||||||
|
|
||||||
|
Is this your first time? Don't worry, Lisplings is made for beginners!
|
||||||
|
We are going to teach you a lot about Common Lisp, but before we can
|
||||||
|
get started, here's how Lisplings works:
|
||||||
|
|
||||||
|
1. The central idea is small exercises with something wrong or
|
||||||
|
missing: the file fails to load, or one of its checks fails.
|
||||||
|
Your job is to fix the exercise.
|
||||||
|
2. Lisplings watches the current exercise file. Edit it in your
|
||||||
|
editor and save; the exercise runs again automatically. When
|
||||||
|
everything passes, press n to move on.
|
||||||
|
3. Stuck? Press h for a hint. Really stuck? Peek at solutions/.
|
||||||
|
4. The REPL is your friend. Run `sbcl' in another terminal and try
|
||||||
|
forms interactively. That's the Lisp way!")
|
||||||
|
|
||||||
|
(:final "We hope you enjoyed Lisplings! You can now read and write
|
||||||
|
Common Lisp, and you know how to find out more: (describe 'foo),
|
||||||
|
(apropos \"foo\"), and the HyperSpec are your friends.
|
||||||
|
|
||||||
|
Found an issue, or want to add an exercise? Improvements welcome!")
|
||||||
|
|
||||||
|
(:exercises
|
||||||
|
((:name "intro1"
|
||||||
|
:dir "00_intro"
|
||||||
|
:hint "This exercise has no errors. Play with the banner, save the file, and press n in the terminal. You might need to press ENTER after typing n.")
|
||||||
|
(:name "intro2"
|
||||||
|
:dir "00_intro"
|
||||||
|
:hint "The format directive ~a expects a value from the arguments after the format string. The string below has no arguments at all...")
|
||||||
|
(:name "sexps1"
|
||||||
|
:dir "01_sexps"
|
||||||
|
:hint "The operator goes first: (+ 10 32). In (- 100 50) the first argument is what is subtracted FROM, so order matters.")
|
||||||
|
(:name "sexps2"
|
||||||
|
:dir "01_sexps"
|
||||||
|
:hint "Nest the sub-expression where its value belongs: (/ 100 (+ 2 3)). For an exact half, drop the 2.0: (/ 1 2) is the rational 1/2, not 0.5.")
|
||||||
|
(:name "sexps3"
|
||||||
|
:dir "01_sexps"
|
||||||
|
:hint "Quote stops evaluation: '(+ 1 2) is the LIST (+ 1 2). The single quote is reader shorthand for (quote x).")
|
||||||
|
(:name "functions1"
|
||||||
|
:dir "02_functions"
|
||||||
|
:hint "DEFUN: (defun name (params) body). The last form of the body is the return value. Twice X is (* 2 x), and addition is (+ a b).")
|
||||||
|
(:name "functions2"
|
||||||
|
:dir "02_functions"
|
||||||
|
:hint "Match the parameter list to the calls: average is called with TWO numbers here. And (- a b) subtracts b from a - check which way round you wrote it.")
|
||||||
|
(:name "functions3"
|
||||||
|
:dir "02_functions"
|
||||||
|
:hint "&OPTIONAL gives a parameter a default: (defun repeat-word (word &optional (n 2)) ...). For the box, a keyword default may use an earlier parameter: (defun make-box (width &key (height width) (depth width)) ...).")
|
||||||
|
(:name "functions4"
|
||||||
|
:dir "02_functions"
|
||||||
|
:hint "FLOOR returns two values at once: (floor 10 3) is 3 and 1. Pass it straight through. For 125 seconds: (floor seconds 60) is 2 minutes and 5 seconds.")
|
||||||
|
(:name "variables1"
|
||||||
|
:dir "03_variables"
|
||||||
|
:hint "DEFPARAMETER gives a global its value: (defparameter *room-capacity* 100). Any capacity from 3 to 199 passes both checks.")
|
||||||
|
(:name "variables2"
|
||||||
|
:dir "03_variables"
|
||||||
|
:hint "The inner LET's initializer evaluates in the OUTER scope, so it can see the outer x: (let ((x (+ x 5))) ...). For wrap-me, introduce a LET of your own with a suitable binding.")
|
||||||
|
(:name "variables3"
|
||||||
|
:dir "03_variables"
|
||||||
|
:hint "LET binds all at once; LET* binds one by one, so B can be (+ A 2) and still see A's value.")
|
||||||
|
(:name "variables4"
|
||||||
|
:dir "03_variables"
|
||||||
|
:hint "Read the current balance first, then SETF the place to the sum: (setf (getf *account* :balance) (+ amount (getf *account* :balance))).")
|
||||||
|
(:name "if1"
|
||||||
|
:dir "04_conditionals"
|
||||||
|
:hint "The condition needs to be a TEST, not the temperature itself: (> temperature 30). Any number - even 0 - is true, so the broken version always answers hot.")
|
||||||
|
(:name "if2"
|
||||||
|
:dir "04_conditionals"
|
||||||
|
:hint "IF takes exactly one then-form and one else-form; the fourth part makes it malformed. COND handles many branches: (cond ((zerop n) \"zero\") ((minusp n) \"negative\") (t \"positive\")).")
|
||||||
|
(:name "if3"
|
||||||
|
:dir "04_conditionals"
|
||||||
|
:hint "WHEN runs its body when the test is TRUE - plusp, not minusp. For enter, only an IF with both branches can return :denied when the door is shut.")
|
||||||
|
(:name "if4"
|
||||||
|
:dir "04_conditionals"
|
||||||
|
:hint "OR returns the first non-NIL value: (or a b c). For safe-div, UNLESS can guard the division and OR supplies the fallback: (or (unless (zerop b) (/ a b)) :undefined).")
|
||||||
|
(:name "pred1"
|
||||||
|
:dir "05_predicates"
|
||||||
|
:hint "Only NIL is false. (not (null thing)) is true for everything else, including 0 and the empty string.")
|
||||||
|
(:name "pred2"
|
||||||
|
:dir "05_predicates"
|
||||||
|
:hint "EQ compares identity: two separately built lists are different objects. EQUAL compares structure. Numbers compare by value with =, and (= 1 1.0) is T.")
|
||||||
|
(:name "pred3"
|
||||||
|
:dir "05_predicates"
|
||||||
|
:hint "Write a COND. Check (NULL V) before the others: (listp nil) is also true, so the :nothing branch must come first.")
|
||||||
|
(:name "lists1"
|
||||||
|
:dir "06_lists"
|
||||||
|
:hint "CAR takes the first element, CDR takes the rest. To put one element in front, CONS it: (cons x xs) - (list x xs) would nest the list instead.")
|
||||||
|
(:name "lists2"
|
||||||
|
:dir "06_lists"
|
||||||
|
:hint "Quote writes a list down as data: '(a b c). LIST builds one at runtime: (list 1 2 3). APPEND joins lists: (append '(1 2) '(3 4)).")
|
||||||
|
(:name "lists3"
|
||||||
|
:dir "06_lists"
|
||||||
|
:hint "NTH counts from zero. LAST returns the last CONS cell - take its CAR for the element. BUTLAST drops the last element.")
|
||||||
|
(:name "lists4"
|
||||||
|
:dir "06_lists"
|
||||||
|
:hint "PUSH and POP work on a variable holding a list: (push x ys) conses x on. Two pushes end up in reverse order - push 0 first, then 1.")
|
||||||
|
(:name "lists5"
|
||||||
|
:dir "06_lists"
|
||||||
|
:hint "ASSOC finds a pair by key: (assoc item *menu*) returns the pair; its CDR is the price. PUSH a new (cons item cost) pair onto the alist.")
|
||||||
|
(:name "recurs1"
|
||||||
|
:dir "07_recursion"
|
||||||
|
:hint "The base case must return 0, not NIL - (+ 3 nil) is a type error. Add the head to the recursive sum of the rest.")
|
||||||
|
(:name "recurs2"
|
||||||
|
:dir "07_recursion"
|
||||||
|
:hint "The recursive call handles a list one shorter. Add 1 for the element you just consumed: (+ 1 (my-length (cdr xs))).")
|
||||||
|
(:name "recurs3"
|
||||||
|
:dir "07_recursion"
|
||||||
|
:hint "Follow the MEMBER convention: return the tail of the list starting at the match, or NIL. Test with (equal x (car xs)), else recurse on (cdr xs).")
|
||||||
|
(:name "recurs4"
|
||||||
|
:dir "07_recursion"
|
||||||
|
:hint "A tree has two parts: (car tree) and (cdr tree). Count the leaves in BOTH and add the results.")
|
||||||
|
(:name "func1"
|
||||||
|
:dir "08_functional"
|
||||||
|
:hint "FUNCALL calls a function value: (funcall f 10). LAMBDA makes function values: (lambda (x) (* 2 x)).")
|
||||||
|
(:name "func2"
|
||||||
|
:dir "08_functional"
|
||||||
|
:hint "MAPCAR applies a function to each element: (mapcar (lambda (x) (* 2 x)) xs). STRING-UPCASE is a function too: #'string-upcase.")
|
||||||
|
(:name "func3"
|
||||||
|
:dir "08_functional"
|
||||||
|
:hint "APPLY spreads a list into arguments: (apply #'+ xs) is (+ 1 2 3) for (1 2 3). FUNCALL keeps them spelled out.")
|
||||||
|
(:name "func4"
|
||||||
|
:dir "08_functional"
|
||||||
|
:hint "REDUCE folds: (reduce #'max xs) for the biggest, (reduce #'* xs :initial-value 1) for the product.")
|
||||||
|
(:name "str1"
|
||||||
|
:dir "09_strings"
|
||||||
|
:hint "FORMAT's first argument NIL returns a string. ~a prints a value; ~10a pads it to ten columns.")
|
||||||
|
(:name "str2"
|
||||||
|
:dir "09_strings"
|
||||||
|
:hint "SUBSEQ takes start and end: (subseq s 0 3). CONCATENATE joins strings. SEARCH is case-sensitive - search for lowercase \"lisp\".")
|
||||||
|
(:name "str3"
|
||||||
|
:dir "09_strings"
|
||||||
|
:hint "CONCATENATE joins: (concatenate 'string first \" \" last). STRING-EQUAL compares ignoring case; EQ on strings is unreliable.")
|
||||||
|
(:name "str4"
|
||||||
|
:dir "09_strings"
|
||||||
|
:hint "FORMAT iterates with ~{ ... ~}, and ~^ skips the separator at the last element: (format nil \"~{~a~^, ~}\" xs).")
|
||||||
|
(:name "loops1"
|
||||||
|
:dir "10_loops"
|
||||||
|
:hint "DOLIST walks a list: (dolist (x xs) (incf total x)). DOTIMES counts from 0; PUSH inside it builds the countdown naturally.")
|
||||||
|
(:name "loops2"
|
||||||
|
:dir "10_loops"
|
||||||
|
:hint "COLLECT gathers into a list, SUM adds: (loop for i from 1 to n sum i).")
|
||||||
|
(:name "loops3"
|
||||||
|
:dir "10_loops"
|
||||||
|
:hint "WHEN filters inside LOOP: (loop for x in xs when (evenp x) collect x). THEREIS returns the first non-NIL value and stops: (thereis (if (> x 100) x)).")
|
||||||
|
(:name "num1"
|
||||||
|
:dir "11_numbers"
|
||||||
|
:hint "Drop the 2.0: (expt 2 100) and (/ 7 2) stay exact when all arguments are integers.")
|
||||||
|
(:name "num2"
|
||||||
|
:dir "11_numbers"
|
||||||
|
:hint "FLOOR rounds toward minus infinity: (* 5 (floor x 5)). MOD follows FLOOR's sign, so (mod -9 5) is 1.")
|
||||||
|
(:name "num3"
|
||||||
|
:dir "11_numbers"
|
||||||
|
:hint "Clamp with both bounds: (min high (max low x)). Distance is (abs (- a b)). INCF and DECF step a variable in place.")
|
||||||
|
(:name "structs1"
|
||||||
|
:dir "12_structs"
|
||||||
|
:hint "The constructor takes a keyword for every slot: (make-person :name \"Ada\" :age 36). The reader is (person-age ada).")
|
||||||
|
(:name "structs2"
|
||||||
|
:dir "12_structs"
|
||||||
|
:hint "Leave :name out and the default applies. DEFSTRUCT generated the predicate too: (spaceship-p x).")
|
||||||
|
(:name "structs3"
|
||||||
|
:dir "12_structs"
|
||||||
|
:hint "Struct slots are SETF places: (setf (counter-value c) 0). INCF works on any place.")
|
||||||
|
(:name "structs4"
|
||||||
|
:dir "12_structs"
|
||||||
|
:hint ":INCLUDE inherits: make-student accepts every person slot plus :major. The reader for the new slot is student-major.")
|
||||||
|
(:name "hash1"
|
||||||
|
:dir "13_hash_tables"
|
||||||
|
:hint "SETF on a GETHASH place stores: (setf (gethash 'ada table) 36). And GETHASH takes the table as its SECOND argument.")
|
||||||
|
(:name "hash2"
|
||||||
|
:dir "13_hash_tables"
|
||||||
|
:hint "GETHASH returns two values; NTH-VALUE 1 picks the presence flag. MULTIPLE-VALUE-BIND binds both at once.")
|
||||||
|
(:name "hash3"
|
||||||
|
:dir "13_hash_tables"
|
||||||
|
:hint "GETHASH takes a default: (gethash x table 0) counts missing keys as 0, so (incf (gethash x table 0)) tallies in one line.")
|
||||||
|
(:name "pkg1"
|
||||||
|
:dir "14_packages"
|
||||||
|
:hint "The function now lives in the SHAPES package; the body is just (* s s). The package form above already exported AREA so the checks can reach it.")
|
||||||
|
(:name "pkg2"
|
||||||
|
:dir "14_packages"
|
||||||
|
:hint "The check calls (kitchen:make-soup) with a single colon, which only sees EXPORTED symbols. Add (:export #:make-soup) to the defpackage.")
|
||||||
|
(:name "pkg3"
|
||||||
|
:dir "14_packages"
|
||||||
|
:hint "STUDIO uses SHAPES, so AREA is right there: (+ (area a) (area b)).")
|
||||||
|
(:name "clos1"
|
||||||
|
:dir "15_clos"
|
||||||
|
:hint "MAKE-INSTANCE with initargs: (make-instance 'dog :name \"Rex\" :tricks '(\"sit\" \"roll-over\")). Initargs are keywords named after the slots.")
|
||||||
|
(:name "clos2"
|
||||||
|
:dir "15_clos"
|
||||||
|
:hint "Write a DEFMETHOD for the base class ANIMAL. Any other animal hits the least specific applicable method.")
|
||||||
|
(:name "clos3"
|
||||||
|
:dir "15_clos"
|
||||||
|
:hint "An :AFTER method just does its job: (push (list 'deposited amount) (account-log a)).")
|
||||||
|
(:name "clos4"
|
||||||
|
:dir "15_clos"
|
||||||
|
:hint "The EQL-specialized method returns \"a free muffin too\" when CUSTOMER is exactly 'vip.")
|
||||||
|
(:name "cond1"
|
||||||
|
:dir "16_conditions"
|
||||||
|
:hint "Wrap the call in HANDLER-CASE with a PARSE-ERROR clause that returns :not-a-number.")
|
||||||
|
(:name "cond2"
|
||||||
|
:dir "16_conditions"
|
||||||
|
:hint "UNWIND-PROTECT runs its body, then ALWAYS runs the cleanup form: (unwind-protect (progn (setf *lid* :open) (funcall f)) (setf *lid* :closed)).")
|
||||||
|
(:name "cond3"
|
||||||
|
:dir "16_conditions"
|
||||||
|
:hint "EAT signals (error 'empty-plate :what \"soup\") when XS is NIL. CATCH-EMPTY handles it with HANDLER-CASE and reads the slot with EMPTY-PLATE-WHAT.")
|
||||||
|
(:name "cond4"
|
||||||
|
:dir "16_conditions"
|
||||||
|
:hint "SAFE-CAR wraps its error in RESTART-CASE, offering (use-nil () nil). CAR-WITH-DEFAULT uses HANDLER-BIND and INVOKE-RESTART 'USE-NIL.")
|
||||||
|
(:name "macro1"
|
||||||
|
:dir "17_macros"
|
||||||
|
:hint "Return the code that should run: `(if ,test (progn ,@body)). MACROEXPAND-1 in a REPL shows what you built.")
|
||||||
|
(:name "macro2"
|
||||||
|
:dir "17_macros"
|
||||||
|
:hint "A comma inserts one value: `(boxed ,x). A comma-at SPLICES a list in: `(add ,@numbers).")
|
||||||
|
(:name "macro3"
|
||||||
|
:dir "17_macros"
|
||||||
|
:hint "Bind (gensym) in the macro body and use it instead of N, so the user's variable is never shadowed: `(let ((,temp 5)) (+ ,n ,temp)).")
|
||||||
|
(:name "macro4"
|
||||||
|
:dir "17_macros"
|
||||||
|
:hint "LOOP does the work: `(loop while ,test do ,@body).")
|
||||||
|
(:name "dyn1"
|
||||||
|
:dir "18_dynamic"
|
||||||
|
:hint "INCF the captured variable and return the result: (lambda () (incf count)). Each closure has its own COUNT.")
|
||||||
|
(:name "dyn2"
|
||||||
|
:dir "18_dynamic"
|
||||||
|
:hint "LET on a special variable rebinds it dynamically and restores it: (let ((*depth* n)) (funcall f)).")
|
||||||
|
(:name "dyn3"
|
||||||
|
:dir "18_dynamic"
|
||||||
|
:hint "MULTIPLE-VALUE-BIND on GETHASH: if PRESENT return the value, otherwise compute, SETF the table, return. The second call must not touch SLOW-FIB again.")
|
||||||
|
(:name "quiz1"
|
||||||
|
:dir "quizzes"
|
||||||
|
:hint "APPEND makes a new book with the contact at the end. DOLIST + STRING-EQUAL + GETF finds by name; FORMAT makes the card.")
|
||||||
|
(:name "quiz2"
|
||||||
|
:dir "quizzes"
|
||||||
|
:hint "A COND over three shapes: numbers, quote forms, and operator forms. MEMBER (car expr) '(+ - *) recognizes the operators; APPLY + MAPCAR evaluates the arguments."))))
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Lisplings: small exercises to get you used to reading and writing
|
||||||
|
# Common Lisp code. Requires SBCL in PATH.
|
||||||
|
set -eu
|
||||||
|
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
exec sbcl --noinform --no-sysinit --no-userinit --script "$DIR/src/main.lisp" "$@"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Lisplings wrapper installed by the nix package.
|
||||||
|
set -eu
|
||||||
|
exec @sbcl@/bin/sbcl --noinform --no-sysinit --no-userinit \
|
||||||
|
--script @out@/lib/lisplings/src/main.lisp "$@"
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
lib,
|
||||||
|
stdenv,
|
||||||
|
sbcl,
|
||||||
|
src,
|
||||||
|
}:
|
||||||
|
|
||||||
|
stdenv.mkDerivation {
|
||||||
|
pname = "lisplings";
|
||||||
|
version = "0.1.0";
|
||||||
|
|
||||||
|
inherit src sbcl;
|
||||||
|
|
||||||
|
installPhase = ''
|
||||||
|
runHook preInstall
|
||||||
|
|
||||||
|
mkdir -p $out/lib/lisplings $out/bin
|
||||||
|
cp -r $src/src $src/exercises $src/solutions $src/info.sexp $out/lib/lisplings/
|
||||||
|
|
||||||
|
substituteAll ${./lisplings.sh} $out/bin/lisplings
|
||||||
|
chmod +x $out/bin/lisplings
|
||||||
|
|
||||||
|
runHook postInstall
|
||||||
|
'';
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
description = "Small exercises to get you used to reading and writing Common Lisp code";
|
||||||
|
mainProgram = "lisplings";
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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,5 @@
|
|||||||
|
;;; INTRO 2: READING AN ERROR (solution)
|
||||||
|
|
||||||
|
(format t "Hello, ~a! Welcome to Common Lisp.~%" "world")
|
||||||
|
|
||||||
|
(format t "Save this file with your fix; lisplings runs it again.~%")
|
||||||
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user