From 4df60ead93c59e1a5c0ea04edab031985a4c7429 Mon Sep 17 00:00:00 2001 From: venomade Date: Sun, 22 Nov 2026 03:30:19 +0000 Subject: [PATCH] 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. --- .gitignore | 10 + README.md | 138 +++++++ dev/verify.sh | 43 +++ exercises/00_intro/intro1.lisp | 28 ++ exercises/00_intro/intro2.lisp | 11 + exercises/01_sexps/README.md | 12 + exercises/01_sexps/sexps1.lisp | 27 ++ exercises/01_sexps/sexps2.lisp | 27 ++ exercises/01_sexps/sexps3.lisp | 30 ++ exercises/02_functions/README.md | 7 + exercises/02_functions/functions1.lisp | 24 ++ exercises/02_functions/functions2.lisp | 24 ++ exercises/02_functions/functions3.lisp | 26 ++ exercises/02_functions/functions4.lisp | 24 ++ exercises/03_variables/README.md | 6 + exercises/03_variables/variables1.lisp | 18 + exercises/03_variables/variables2.lisp | 24 ++ exercises/03_variables/variables3.lisp | 18 + exercises/03_variables/variables4.lisp | 20 + exercises/04_conditionals/README.md | 6 + exercises/04_conditionals/if1.lisp | 22 ++ exercises/04_conditionals/if2.lisp | 27 ++ exercises/04_conditionals/if3.lisp | 25 ++ exercises/04_conditionals/if4.lisp | 26 ++ exercises/05_predicates/README.md | 6 + exercises/05_predicates/pred1.lisp | 18 + exercises/05_predicates/pred2.lisp | 26 ++ exercises/05_predicates/pred3.lisp | 24 ++ exercises/06_lists/README.md | 7 + exercises/06_lists/lists1.lisp | 29 ++ exercises/06_lists/lists2.lisp | 26 ++ exercises/06_lists/lists3.lisp | 27 ++ exercises/06_lists/lists4.lisp | 25 ++ exercises/06_lists/lists5.lisp | 29 ++ exercises/07_recursion/README.md | 6 + exercises/07_recursion/recurs1.lisp | 24 ++ exercises/07_recursion/recurs2.lisp | 18 + exercises/07_recursion/recurs3.lisp | 21 ++ exercises/07_recursion/recurs4.lisp | 20 + exercises/08_functional/README.md | 6 + exercises/08_functional/func1.lisp | 23 ++ exercises/08_functional/func2.lisp | 22 ++ exercises/08_functional/func3.lisp | 23 ++ exercises/08_functional/func4.lisp | 24 ++ exercises/09_strings/README.md | 6 + exercises/09_strings/str1.lisp | 25 ++ exercises/09_strings/str2.lisp | 28 ++ exercises/09_strings/str3.lisp | 23 ++ exercises/09_strings/str4.lisp | 23 ++ exercises/10_loops/README.md | 6 + exercises/10_loops/loops1.lisp | 30 ++ exercises/10_loops/loops2.lisp | 25 ++ exercises/10_loops/loops3.lisp | 25 ++ exercises/11_numbers/README.md | 6 + exercises/11_numbers/num1.lisp | 21 ++ exercises/11_numbers/num2.lisp | 25 ++ exercises/11_numbers/num3.lisp | 32 ++ exercises/12_structs/README.md | 5 + exercises/12_structs/structs1.lisp | 27 ++ exercises/12_structs/structs2.lisp | 29 ++ exercises/12_structs/structs3.lisp | 27 ++ exercises/12_structs/structs4.lisp | 29 ++ exercises/13_hash_tables/README.md | 7 + exercises/13_hash_tables/hash1.lisp | 23 ++ exercises/13_hash_tables/hash2.lisp | 30 ++ exercises/13_hash_tables/hash3.lisp | 22 ++ exercises/14_packages/README.md | 7 + exercises/14_packages/pkg1.lisp | 25 ++ exercises/14_packages/pkg2.lisp | 21 ++ exercises/14_packages/pkg3.lisp | 34 ++ exercises/15_clos/README.md | 7 + exercises/15_clos/clos1.lisp | 22 ++ exercises/15_clos/clos2.lisp | 27 ++ exercises/15_clos/clos3.lisp | 31 ++ exercises/15_clos/clos4.lisp | 22 ++ exercises/16_conditions/README.md | 7 + exercises/16_conditions/cond1.lisp | 22 ++ exercises/16_conditions/cond2.lisp | 25 ++ exercises/16_conditions/cond3.lisp | 26 ++ exercises/16_conditions/cond4.lisp | 33 ++ exercises/17_macros/README.md | 7 + exercises/17_macros/macro1.lisp | 19 + exercises/17_macros/macro2.lisp | 24 ++ exercises/17_macros/macro3.lisp | 21 ++ exercises/17_macros/macro4.lisp | 28 ++ exercises/18_dynamic/README.md | 7 + exercises/18_dynamic/dyn1.lisp | 21 ++ exercises/18_dynamic/dyn2.lisp | 26 ++ exercises/18_dynamic/dyn3.lisp | 32 ++ exercises/quizzes/README.md | 7 + exercises/quizzes/quiz1.lisp | 41 ++ exercises/quizzes/quiz2.lisp | 29 ++ flake.lock | 27 ++ flake.nix | 45 +++ info.sexp | 240 ++++++++++++ lisplings | 6 + nix/lisplings.sh | 5 + nix/package.nix | 30 ++ solutions/00_intro/intro1.lisp | 28 ++ solutions/00_intro/intro2.lisp | 5 + solutions/01_sexps/sexps1.lisp | 19 + solutions/01_sexps/sexps2.lisp | 19 + solutions/01_sexps/sexps3.lisp | 19 + solutions/02_functions/functions1.lisp | 17 + solutions/02_functions/functions2.lisp | 17 + solutions/02_functions/functions3.lisp | 18 + solutions/02_functions/functions4.lisp | 16 + solutions/03_variables/variables1.lisp | 14 + solutions/03_variables/variables2.lisp | 18 + solutions/03_variables/variables3.lisp | 13 + solutions/03_variables/variables4.lisp | 16 + solutions/04_conditionals/if1.lisp | 15 + solutions/04_conditionals/if2.lisp | 15 + solutions/04_conditionals/if3.lisp | 18 + solutions/04_conditionals/if4.lisp | 19 + solutions/05_predicates/pred1.lisp | 14 + solutions/05_predicates/pred2.lisp | 17 + solutions/05_predicates/pred3.lisp | 18 + solutions/06_lists/lists1.lisp | 20 + solutions/06_lists/lists2.lisp | 19 + solutions/06_lists/lists3.lisp | 20 + solutions/06_lists/lists4.lisp | 21 ++ solutions/06_lists/lists5.lisp | 23 ++ solutions/07_recursion/recurs1.lisp | 15 + solutions/07_recursion/recurs2.lisp | 15 + solutions/07_recursion/recurs3.lisp | 15 + solutions/07_recursion/recurs4.lisp | 17 + solutions/08_functional/func1.lisp | 17 + solutions/08_functional/func2.lisp | 16 + solutions/08_functional/func3.lisp | 17 + solutions/08_functional/func4.lisp | 18 + solutions/09_strings/str1.lisp | 17 + solutions/09_strings/str2.lisp | 21 ++ solutions/09_strings/str3.lisp | 17 + solutions/09_strings/str4.lisp | 17 + solutions/10_loops/loops1.lisp | 23 ++ solutions/10_loops/loops2.lisp | 19 + solutions/10_loops/loops3.lisp | 20 + solutions/11_numbers/num1.lisp | 15 + solutions/11_numbers/num2.lisp | 19 + solutions/11_numbers/num3.lisp | 27 ++ solutions/12_structs/structs1.lisp | 21 ++ solutions/12_structs/structs2.lisp | 23 ++ solutions/12_structs/structs3.lisp | 24 ++ solutions/12_structs/structs4.lisp | 24 ++ solutions/13_hash_tables/hash1.lisp | 20 + solutions/13_hash_tables/hash2.lisp | 25 ++ solutions/13_hash_tables/hash3.lisp | 18 + solutions/14_packages/pkg1.lisp | 20 + solutions/14_packages/pkg2.lisp | 19 + solutions/14_packages/pkg3.lisp | 29 ++ solutions/15_clos/clos1.lisp | 17 + solutions/15_clos/clos2.lisp | 20 + solutions/15_clos/clos3.lisp | 27 ++ solutions/15_clos/clos4.lisp | 17 + solutions/16_conditions/cond1.lisp | 14 + solutions/16_conditions/cond2.lisp | 22 ++ solutions/16_conditions/cond3.lisp | 22 ++ solutions/16_conditions/cond4.lisp | 23 ++ solutions/17_macros/macro1.lisp | 13 + solutions/17_macros/macro2.lisp | 16 + solutions/17_macros/macro3.lisp | 16 + solutions/17_macros/macro4.lisp | 18 + solutions/18_dynamic/dyn1.lisp | 15 + solutions/18_dynamic/dyn2.lisp | 20 + solutions/18_dynamic/dyn3.lisp | 29 ++ solutions/quizzes/quiz1.lisp | 32 ++ solutions/quizzes/quiz2.lisp | 22 ++ src/core.lisp | 494 +++++++++++++++++++++++++ src/exercise-runner.lisp | 46 +++ src/harness.lisp | 101 +++++ src/main.lisp | 8 + 172 files changed, 4403 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 dev/verify.sh create mode 100644 exercises/00_intro/intro1.lisp create mode 100644 exercises/00_intro/intro2.lisp create mode 100644 exercises/01_sexps/README.md create mode 100644 exercises/01_sexps/sexps1.lisp create mode 100644 exercises/01_sexps/sexps2.lisp create mode 100644 exercises/01_sexps/sexps3.lisp create mode 100644 exercises/02_functions/README.md create mode 100644 exercises/02_functions/functions1.lisp create mode 100644 exercises/02_functions/functions2.lisp create mode 100644 exercises/02_functions/functions3.lisp create mode 100644 exercises/02_functions/functions4.lisp create mode 100644 exercises/03_variables/README.md create mode 100644 exercises/03_variables/variables1.lisp create mode 100644 exercises/03_variables/variables2.lisp create mode 100644 exercises/03_variables/variables3.lisp create mode 100644 exercises/03_variables/variables4.lisp create mode 100644 exercises/04_conditionals/README.md create mode 100644 exercises/04_conditionals/if1.lisp create mode 100644 exercises/04_conditionals/if2.lisp create mode 100644 exercises/04_conditionals/if3.lisp create mode 100644 exercises/04_conditionals/if4.lisp create mode 100644 exercises/05_predicates/README.md create mode 100644 exercises/05_predicates/pred1.lisp create mode 100644 exercises/05_predicates/pred2.lisp create mode 100644 exercises/05_predicates/pred3.lisp create mode 100644 exercises/06_lists/README.md create mode 100644 exercises/06_lists/lists1.lisp create mode 100644 exercises/06_lists/lists2.lisp create mode 100644 exercises/06_lists/lists3.lisp create mode 100644 exercises/06_lists/lists4.lisp create mode 100644 exercises/06_lists/lists5.lisp create mode 100644 exercises/07_recursion/README.md create mode 100644 exercises/07_recursion/recurs1.lisp create mode 100644 exercises/07_recursion/recurs2.lisp create mode 100644 exercises/07_recursion/recurs3.lisp create mode 100644 exercises/07_recursion/recurs4.lisp create mode 100644 exercises/08_functional/README.md create mode 100644 exercises/08_functional/func1.lisp create mode 100644 exercises/08_functional/func2.lisp create mode 100644 exercises/08_functional/func3.lisp create mode 100644 exercises/08_functional/func4.lisp create mode 100644 exercises/09_strings/README.md create mode 100644 exercises/09_strings/str1.lisp create mode 100644 exercises/09_strings/str2.lisp create mode 100644 exercises/09_strings/str3.lisp create mode 100644 exercises/09_strings/str4.lisp create mode 100644 exercises/10_loops/README.md create mode 100644 exercises/10_loops/loops1.lisp create mode 100644 exercises/10_loops/loops2.lisp create mode 100644 exercises/10_loops/loops3.lisp create mode 100644 exercises/11_numbers/README.md create mode 100644 exercises/11_numbers/num1.lisp create mode 100644 exercises/11_numbers/num2.lisp create mode 100644 exercises/11_numbers/num3.lisp create mode 100644 exercises/12_structs/README.md create mode 100644 exercises/12_structs/structs1.lisp create mode 100644 exercises/12_structs/structs2.lisp create mode 100644 exercises/12_structs/structs3.lisp create mode 100644 exercises/12_structs/structs4.lisp create mode 100644 exercises/13_hash_tables/README.md create mode 100644 exercises/13_hash_tables/hash1.lisp create mode 100644 exercises/13_hash_tables/hash2.lisp create mode 100644 exercises/13_hash_tables/hash3.lisp create mode 100644 exercises/14_packages/README.md create mode 100644 exercises/14_packages/pkg1.lisp create mode 100644 exercises/14_packages/pkg2.lisp create mode 100644 exercises/14_packages/pkg3.lisp create mode 100644 exercises/15_clos/README.md create mode 100644 exercises/15_clos/clos1.lisp create mode 100644 exercises/15_clos/clos2.lisp create mode 100644 exercises/15_clos/clos3.lisp create mode 100644 exercises/15_clos/clos4.lisp create mode 100644 exercises/16_conditions/README.md create mode 100644 exercises/16_conditions/cond1.lisp create mode 100644 exercises/16_conditions/cond2.lisp create mode 100644 exercises/16_conditions/cond3.lisp create mode 100644 exercises/16_conditions/cond4.lisp create mode 100644 exercises/17_macros/README.md create mode 100644 exercises/17_macros/macro1.lisp create mode 100644 exercises/17_macros/macro2.lisp create mode 100644 exercises/17_macros/macro3.lisp create mode 100644 exercises/17_macros/macro4.lisp create mode 100644 exercises/18_dynamic/README.md create mode 100644 exercises/18_dynamic/dyn1.lisp create mode 100644 exercises/18_dynamic/dyn2.lisp create mode 100644 exercises/18_dynamic/dyn3.lisp create mode 100644 exercises/quizzes/README.md create mode 100644 exercises/quizzes/quiz1.lisp create mode 100644 exercises/quizzes/quiz2.lisp create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 info.sexp create mode 100755 lisplings create mode 100644 nix/lisplings.sh create mode 100644 nix/package.nix create mode 100644 solutions/00_intro/intro1.lisp create mode 100644 solutions/00_intro/intro2.lisp create mode 100644 solutions/01_sexps/sexps1.lisp create mode 100644 solutions/01_sexps/sexps2.lisp create mode 100644 solutions/01_sexps/sexps3.lisp create mode 100644 solutions/02_functions/functions1.lisp create mode 100644 solutions/02_functions/functions2.lisp create mode 100644 solutions/02_functions/functions3.lisp create mode 100644 solutions/02_functions/functions4.lisp create mode 100644 solutions/03_variables/variables1.lisp create mode 100644 solutions/03_variables/variables2.lisp create mode 100644 solutions/03_variables/variables3.lisp create mode 100644 solutions/03_variables/variables4.lisp create mode 100644 solutions/04_conditionals/if1.lisp create mode 100644 solutions/04_conditionals/if2.lisp create mode 100644 solutions/04_conditionals/if3.lisp create mode 100644 solutions/04_conditionals/if4.lisp create mode 100644 solutions/05_predicates/pred1.lisp create mode 100644 solutions/05_predicates/pred2.lisp create mode 100644 solutions/05_predicates/pred3.lisp create mode 100644 solutions/06_lists/lists1.lisp create mode 100644 solutions/06_lists/lists2.lisp create mode 100644 solutions/06_lists/lists3.lisp create mode 100644 solutions/06_lists/lists4.lisp create mode 100644 solutions/06_lists/lists5.lisp create mode 100644 solutions/07_recursion/recurs1.lisp create mode 100644 solutions/07_recursion/recurs2.lisp create mode 100644 solutions/07_recursion/recurs3.lisp create mode 100644 solutions/07_recursion/recurs4.lisp create mode 100644 solutions/08_functional/func1.lisp create mode 100644 solutions/08_functional/func2.lisp create mode 100644 solutions/08_functional/func3.lisp create mode 100644 solutions/08_functional/func4.lisp create mode 100644 solutions/09_strings/str1.lisp create mode 100644 solutions/09_strings/str2.lisp create mode 100644 solutions/09_strings/str3.lisp create mode 100644 solutions/09_strings/str4.lisp create mode 100644 solutions/10_loops/loops1.lisp create mode 100644 solutions/10_loops/loops2.lisp create mode 100644 solutions/10_loops/loops3.lisp create mode 100644 solutions/11_numbers/num1.lisp create mode 100644 solutions/11_numbers/num2.lisp create mode 100644 solutions/11_numbers/num3.lisp create mode 100644 solutions/12_structs/structs1.lisp create mode 100644 solutions/12_structs/structs2.lisp create mode 100644 solutions/12_structs/structs3.lisp create mode 100644 solutions/12_structs/structs4.lisp create mode 100644 solutions/13_hash_tables/hash1.lisp create mode 100644 solutions/13_hash_tables/hash2.lisp create mode 100644 solutions/13_hash_tables/hash3.lisp create mode 100644 solutions/14_packages/pkg1.lisp create mode 100644 solutions/14_packages/pkg2.lisp create mode 100644 solutions/14_packages/pkg3.lisp create mode 100644 solutions/15_clos/clos1.lisp create mode 100644 solutions/15_clos/clos2.lisp create mode 100644 solutions/15_clos/clos3.lisp create mode 100644 solutions/15_clos/clos4.lisp create mode 100644 solutions/16_conditions/cond1.lisp create mode 100644 solutions/16_conditions/cond2.lisp create mode 100644 solutions/16_conditions/cond3.lisp create mode 100644 solutions/16_conditions/cond4.lisp create mode 100644 solutions/17_macros/macro1.lisp create mode 100644 solutions/17_macros/macro2.lisp create mode 100644 solutions/17_macros/macro3.lisp create mode 100644 solutions/17_macros/macro4.lisp create mode 100644 solutions/18_dynamic/dyn1.lisp create mode 100644 solutions/18_dynamic/dyn2.lisp create mode 100644 solutions/18_dynamic/dyn3.lisp create mode 100644 solutions/quizzes/quiz1.lisp create mode 100644 solutions/quizzes/quiz2.lisp create mode 100644 src/core.lisp create mode 100644 src/exercise-runner.lisp create mode 100644 src/harness.lisp create mode 100644 src/main.lisp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12ad2a5 --- /dev/null +++ b/.gitignore @@ -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 +*~ diff --git a/README.md b/README.md new file mode 100644 index 0000000..2aae97c --- /dev/null +++ b/README.md @@ -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 +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 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//.lisp` +and the solved `solutions//.lisp`, add a `(:name ... +:dir ... :hint ...)` entry to `info.sexp`, and run `dev/verify.sh`. diff --git a/dev/verify.sh b/dev/verify.sh new file mode 100755 index 0000000..12cc3dc --- /dev/null +++ b/dev/verify.sh @@ -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 diff --git a/exercises/00_intro/intro1.lisp b/exercises/00_intro/intro1.lisp new file mode 100644 index 0000000..dc6eb95 --- /dev/null +++ b/exercises/00_intro/intro1.lisp @@ -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.~%") diff --git a/exercises/00_intro/intro2.lisp b/exercises/00_intro/intro2.lisp new file mode 100644 index 0000000..71cfb88 --- /dev/null +++ b/exercises/00_intro/intro2.lisp @@ -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.~%") diff --git a/exercises/01_sexps/README.md b/exercises/01_sexps/README.md new file mode 100644 index 0000000..d97e609 --- /dev/null +++ b/exercises/01_sexps/README.md @@ -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. diff --git a/exercises/01_sexps/sexps1.lisp b/exercises/01_sexps/sexps1.lisp new file mode 100644 index 0000000..fe91043 --- /dev/null +++ b/exercises/01_sexps/sexps1.lisp @@ -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)) diff --git a/exercises/01_sexps/sexps2.lisp b/exercises/01_sexps/sexps2.lisp new file mode 100644 index 0000000..f30b9ae --- /dev/null +++ b/exercises/01_sexps/sexps2.lisp @@ -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)) diff --git a/exercises/01_sexps/sexps3.lisp b/exercises/01_sexps/sexps3.lisp new file mode 100644 index 0000000..06549d9 --- /dev/null +++ b/exercises/01_sexps/sexps3.lisp @@ -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)) diff --git a/exercises/02_functions/README.md b/exercises/02_functions/README.md new file mode 100644 index 0000000..77d03a4 --- /dev/null +++ b/exercises/02_functions/README.md @@ -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. diff --git a/exercises/02_functions/functions1.lisp b/exercises/02_functions/functions1.lisp new file mode 100644 index 0000000..c86f2be --- /dev/null +++ b/exercises/02_functions/functions1.lisp @@ -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)) diff --git a/exercises/02_functions/functions2.lisp b/exercises/02_functions/functions2.lisp new file mode 100644 index 0000000..7ce1d00 --- /dev/null +++ b/exercises/02_functions/functions2.lisp @@ -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)) diff --git a/exercises/02_functions/functions3.lisp b/exercises/02_functions/functions3.lisp new file mode 100644 index 0000000..2e71a54 --- /dev/null +++ b/exercises/02_functions/functions3.lisp @@ -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)) diff --git a/exercises/02_functions/functions4.lisp b/exercises/02_functions/functions4.lisp new file mode 100644 index 0000000..a026793 --- /dev/null +++ b/exercises/02_functions/functions4.lisp @@ -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))) diff --git a/exercises/03_variables/README.md b/exercises/03_variables/README.md new file mode 100644 index 0000000..8cee304 --- /dev/null +++ b/exercises/03_variables/README.md @@ -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. diff --git a/exercises/03_variables/variables1.lisp b/exercises/03_variables/variables1.lisp new file mode 100644 index 0000000..d9dc5f9 --- /dev/null +++ b/exercises/03_variables/variables1.lisp @@ -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))) diff --git a/exercises/03_variables/variables2.lisp b/exercises/03_variables/variables2.lisp new file mode 100644 index 0000000..3611a0c --- /dev/null +++ b/exercises/03_variables/variables2.lisp @@ -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)) diff --git a/exercises/03_variables/variables3.lisp b/exercises/03_variables/variables3.lisp new file mode 100644 index 0000000..dc7a670 --- /dev/null +++ b/exercises/03_variables/variables3.lisp @@ -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)) diff --git a/exercises/03_variables/variables4.lisp b/exercises/03_variables/variables4.lisp new file mode 100644 index 0000000..9a73771 --- /dev/null +++ b/exercises/03_variables/variables4.lisp @@ -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)) diff --git a/exercises/04_conditionals/README.md b/exercises/04_conditionals/README.md new file mode 100644 index 0000000..ea31e9f --- /dev/null +++ b/exercises/04_conditionals/README.md @@ -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. diff --git a/exercises/04_conditionals/if1.lisp b/exercises/04_conditionals/if1.lisp new file mode 100644 index 0000000..2ef34bc --- /dev/null +++ b/exercises/04_conditionals/if1.lisp @@ -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)) diff --git a/exercises/04_conditionals/if2.lisp b/exercises/04_conditionals/if2.lisp new file mode 100644 index 0000000..b33b3c4 --- /dev/null +++ b/exercises/04_conditionals/if2.lisp @@ -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)) diff --git a/exercises/04_conditionals/if3.lisp b/exercises/04_conditionals/if3.lisp new file mode 100644 index 0000000..04f27b2 --- /dev/null +++ b/exercises/04_conditionals/if3.lisp @@ -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)) diff --git a/exercises/04_conditionals/if4.lisp b/exercises/04_conditionals/if4.lisp new file mode 100644 index 0000000..d6b0996 --- /dev/null +++ b/exercises/04_conditionals/if4.lisp @@ -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)) diff --git a/exercises/05_predicates/README.md b/exercises/05_predicates/README.md new file mode 100644 index 0000000..53e559c --- /dev/null +++ b/exercises/05_predicates/README.md @@ -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. diff --git a/exercises/05_predicates/pred1.lisp b/exercises/05_predicates/pred1.lisp new file mode 100644 index 0000000..0da7218 --- /dev/null +++ b/exercises/05_predicates/pred1.lisp @@ -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 '()))) diff --git a/exercises/05_predicates/pred2.lisp b/exercises/05_predicates/pred2.lisp new file mode 100644 index 0000000..3c32bae --- /dev/null +++ b/exercises/05_predicates/pred2.lisp @@ -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))) diff --git a/exercises/05_predicates/pred3.lisp b/exercises/05_predicates/pred3.lisp new file mode 100644 index 0000000..9f38938 --- /dev/null +++ b/exercises/05_predicates/pred3.lisp @@ -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)) diff --git a/exercises/06_lists/README.md b/exercises/06_lists/README.md new file mode 100644 index 0000000..ea15dc4 --- /dev/null +++ b/exercises/06_lists/README.md @@ -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. diff --git a/exercises/06_lists/lists1.lisp b/exercises/06_lists/lists1.lisp new file mode 100644 index 0000000..eeaaca5 --- /dev/null +++ b/exercises/06_lists/lists1.lisp @@ -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)) diff --git a/exercises/06_lists/lists2.lisp b/exercises/06_lists/lists2.lisp new file mode 100644 index 0000000..59b5ee7 --- /dev/null +++ b/exercises/06_lists/lists2.lisp @@ -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)) diff --git a/exercises/06_lists/lists3.lisp b/exercises/06_lists/lists3.lisp new file mode 100644 index 0000000..c07fb8e --- /dev/null +++ b/exercises/06_lists/lists3.lisp @@ -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))) diff --git a/exercises/06_lists/lists4.lisp b/exercises/06_lists/lists4.lisp new file mode 100644 index 0000000..1df4467 --- /dev/null +++ b/exercises/06_lists/lists4.lisp @@ -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))) diff --git a/exercises/06_lists/lists5.lisp b/exercises/06_lists/lists5.lisp new file mode 100644 index 0000000..4f40f5a --- /dev/null +++ b/exercises/06_lists/lists5.lisp @@ -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))))) diff --git a/exercises/07_recursion/README.md b/exercises/07_recursion/README.md new file mode 100644 index 0000000..750cd49 --- /dev/null +++ b/exercises/07_recursion/README.md @@ -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. diff --git a/exercises/07_recursion/recurs1.lisp b/exercises/07_recursion/recurs1.lisp new file mode 100644 index 0000000..adec1ef --- /dev/null +++ b/exercises/07_recursion/recurs1.lisp @@ -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))) diff --git a/exercises/07_recursion/recurs2.lisp b/exercises/07_recursion/recurs2.lisp new file mode 100644 index 0000000..5702dfa --- /dev/null +++ b/exercises/07_recursion/recurs2.lisp @@ -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))) diff --git a/exercises/07_recursion/recurs3.lisp b/exercises/07_recursion/recurs3.lisp new file mode 100644 index 0000000..9cce5d6 --- /dev/null +++ b/exercises/07_recursion/recurs3.lisp @@ -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))) diff --git a/exercises/07_recursion/recurs4.lisp b/exercises/07_recursion/recurs4.lisp new file mode 100644 index 0000000..473358f --- /dev/null +++ b/exercises/07_recursion/recurs4.lisp @@ -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)))) diff --git a/exercises/08_functional/README.md b/exercises/08_functional/README.md new file mode 100644 index 0000000..ce4ba6d --- /dev/null +++ b/exercises/08_functional/README.md @@ -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. diff --git a/exercises/08_functional/func1.lisp b/exercises/08_functional/func1.lisp new file mode 100644 index 0000000..c353945 --- /dev/null +++ b/exercises/08_functional/func1.lisp @@ -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)) diff --git a/exercises/08_functional/func2.lisp b/exercises/08_functional/func2.lisp new file mode 100644 index 0000000..f3958e9 --- /dev/null +++ b/exercises/08_functional/func2.lisp @@ -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"))) diff --git a/exercises/08_functional/func3.lisp b/exercises/08_functional/func3.lisp new file mode 100644 index 0000000..e3ac70f --- /dev/null +++ b/exercises/08_functional/func3.lisp @@ -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))) diff --git a/exercises/08_functional/func4.lisp b/exercises/08_functional/func4.lisp new file mode 100644 index 0000000..82753d8 --- /dev/null +++ b/exercises/08_functional/func4.lisp @@ -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 '())) diff --git a/exercises/09_strings/README.md b/exercises/09_strings/README.md new file mode 100644 index 0000000..92b6565 --- /dev/null +++ b/exercises/09_strings/README.md @@ -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. diff --git a/exercises/09_strings/str1.lisp b/exercises/09_strings/str1.lisp new file mode 100644 index 0000000..4fc4d63 --- /dev/null +++ b/exercises/09_strings/str1.lisp @@ -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")) diff --git a/exercises/09_strings/str2.lisp b/exercises/09_strings/str2.lisp new file mode 100644 index 0000000..812a317 --- /dev/null +++ b/exercises/09_strings/str2.lisp @@ -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")) diff --git a/exercises/09_strings/str3.lisp b/exercises/09_strings/str3.lisp new file mode 100644 index 0000000..2b85495 --- /dev/null +++ b/exercises/09_strings/str3.lisp @@ -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"))) diff --git a/exercises/09_strings/str4.lisp b/exercises/09_strings/str4.lisp new file mode 100644 index 0000000..e8cfe52 --- /dev/null +++ b/exercises/09_strings/str4.lisp @@ -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"))) diff --git a/exercises/10_loops/README.md b/exercises/10_loops/README.md new file mode 100644 index 0000000..017143d --- /dev/null +++ b/exercises/10_loops/README.md @@ -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. diff --git a/exercises/10_loops/loops1.lisp b/exercises/10_loops/loops1.lisp new file mode 100644 index 0000000..6749a6d --- /dev/null +++ b/exercises/10_loops/loops1.lisp @@ -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)) diff --git a/exercises/10_loops/loops2.lisp b/exercises/10_loops/loops2.lisp new file mode 100644 index 0000000..1840610 --- /dev/null +++ b/exercises/10_loops/loops2.lisp @@ -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)) diff --git a/exercises/10_loops/loops3.lisp b/exercises/10_loops/loops3.lisp new file mode 100644 index 0000000..8b6df55 --- /dev/null +++ b/exercises/10_loops/loops3.lisp @@ -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))) diff --git a/exercises/11_numbers/README.md b/exercises/11_numbers/README.md new file mode 100644 index 0000000..0543066 --- /dev/null +++ b/exercises/11_numbers/README.md @@ -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. diff --git a/exercises/11_numbers/num1.lisp b/exercises/11_numbers/num1.lisp new file mode 100644 index 0000000..8d6d0e4 --- /dev/null +++ b/exercises/11_numbers/num1.lisp @@ -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)) diff --git a/exercises/11_numbers/num2.lisp b/exercises/11_numbers/num2.lisp new file mode 100644 index 0000000..0e888f7 --- /dev/null +++ b/exercises/11_numbers/num2.lisp @@ -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)) diff --git a/exercises/11_numbers/num3.lisp b/exercises/11_numbers/num3.lisp new file mode 100644 index 0000000..dfe6e60 --- /dev/null +++ b/exercises/11_numbers/num3.lisp @@ -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)) diff --git a/exercises/12_structs/README.md b/exercises/12_structs/README.md new file mode 100644 index 0000000..be61b3b --- /dev/null +++ b/exercises/12_structs/README.md @@ -0,0 +1,5 @@ +# 12_structs + +DEFSTRUCT: constructors, readers, predicates, defaults, inheritance. + +One form generates a whole toolkit around a record type. diff --git a/exercises/12_structs/structs1.lisp b/exercises/12_structs/structs1.lisp new file mode 100644 index 0000000..0d29556 --- /dev/null +++ b/exercises/12_structs/structs1.lisp @@ -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)))) diff --git a/exercises/12_structs/structs2.lisp b/exercises/12_structs/structs2.lisp new file mode 100644 index 0000000..a12575e --- /dev/null +++ b/exercises/12_structs/structs2.lisp @@ -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)))) diff --git a/exercises/12_structs/structs3.lisp b/exercises/12_structs/structs3.lisp new file mode 100644 index 0000000..802caf3 --- /dev/null +++ b/exercises/12_structs/structs3.lisp @@ -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)))) diff --git a/exercises/12_structs/structs4.lisp b/exercises/12_structs/structs4.lisp new file mode 100644 index 0000000..2ad9e97 --- /dev/null +++ b/exercises/12_structs/structs4.lisp @@ -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))))) diff --git a/exercises/13_hash_tables/README.md b/exercises/13_hash_tables/README.md new file mode 100644 index 0000000..925dcea --- /dev/null +++ b/exercises/13_hash_tables/README.md @@ -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?" diff --git a/exercises/13_hash_tables/hash1.lisp b/exercises/13_hash_tables/hash1.lisp new file mode 100644 index 0000000..f62c608 --- /dev/null +++ b/exercises/13_hash_tables/hash1.lisp @@ -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))))) diff --git a/exercises/13_hash_tables/hash2.lisp b/exercises/13_hash_tables/hash2.lisp new file mode 100644 index 0000000..addb0ca --- /dev/null +++ b/exercises/13_hash_tables/hash2.lisp @@ -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))))) diff --git a/exercises/13_hash_tables/hash3.lisp b/exercises/13_hash_tables/hash3.lisp new file mode 100644 index 0000000..222d7d0 --- /dev/null +++ b/exercises/13_hash_tables/hash3.lisp @@ -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))))) diff --git a/exercises/14_packages/README.md b/exercises/14_packages/README.md new file mode 100644 index 0000000..9bf3674 --- /dev/null +++ b/exercises/14_packages/README.md @@ -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. diff --git a/exercises/14_packages/pkg1.lisp b/exercises/14_packages/pkg1.lisp new file mode 100644 index 0000000..a4fe263 --- /dev/null +++ b/exercises/14_packages/pkg1.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)) diff --git a/exercises/14_packages/pkg2.lisp b/exercises/14_packages/pkg2.lisp new file mode 100644 index 0000000..aa18314 --- /dev/null +++ b/exercises/14_packages/pkg2.lisp @@ -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)) diff --git a/exercises/14_packages/pkg3.lisp b/exercises/14_packages/pkg3.lisp new file mode 100644 index 0000000..f2daf69 --- /dev/null +++ b/exercises/14_packages/pkg3.lisp @@ -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)) diff --git a/exercises/15_clos/README.md b/exercises/15_clos/README.md new file mode 100644 index 0000000..4db8a73 --- /dev/null +++ b/exercises/15_clos/README.md @@ -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. diff --git a/exercises/15_clos/clos1.lisp b/exercises/15_clos/clos1.lisp new file mode 100644 index 0000000..d4b7d9b --- /dev/null +++ b/exercises/15_clos/clos1.lisp @@ -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))))) diff --git a/exercises/15_clos/clos2.lisp b/exercises/15_clos/clos2.lisp new file mode 100644 index 0000000..e46d970 --- /dev/null +++ b/exercises/15_clos/clos2.lisp @@ -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))) diff --git a/exercises/15_clos/clos3.lisp b/exercises/15_clos/clos3.lisp new file mode 100644 index 0000000..7246159 --- /dev/null +++ b/exercises/15_clos/clos3.lisp @@ -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))))) diff --git a/exercises/15_clos/clos4.lisp b/exercises/15_clos/clos4.lisp new file mode 100644 index 0000000..65c052e --- /dev/null +++ b/exercises/15_clos/clos4.lisp @@ -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)) diff --git a/exercises/16_conditions/README.md b/exercises/16_conditions/README.md new file mode 100644 index 0000000..9103a18 --- /dev/null +++ b/exercises/16_conditions/README.md @@ -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. diff --git a/exercises/16_conditions/cond1.lisp b/exercises/16_conditions/cond1.lisp new file mode 100644 index 0000000..fd96230 --- /dev/null +++ b/exercises/16_conditions/cond1.lisp @@ -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")) diff --git a/exercises/16_conditions/cond2.lisp b/exercises/16_conditions/cond2.lisp new file mode 100644 index 0000000..aa3a271 --- /dev/null +++ b/exercises/16_conditions/cond2.lisp @@ -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*)) diff --git a/exercises/16_conditions/cond3.lisp b/exercises/16_conditions/cond3.lisp new file mode 100644 index 0000000..2d88008 --- /dev/null +++ b/exercises/16_conditions/cond3.lisp @@ -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 '())) diff --git a/exercises/16_conditions/cond4.lisp b/exercises/16_conditions/cond4.lisp new file mode 100644 index 0000000..b56ee1d --- /dev/null +++ b/exercises/16_conditions/cond4.lisp @@ -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)) diff --git a/exercises/17_macros/README.md b/exercises/17_macros/README.md new file mode 100644 index 0000000..59f1571 --- /dev/null +++ b/exercises/17_macros/README.md @@ -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. diff --git a/exercises/17_macros/macro1.lisp b/exercises/17_macros/macro1.lisp new file mode 100644 index 0000000..6f29664 --- /dev/null +++ b/exercises/17_macros/macro1.lisp @@ -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)) diff --git a/exercises/17_macros/macro2.lisp b/exercises/17_macros/macro2.lisp new file mode 100644 index 0000000..618de47 --- /dev/null +++ b/exercises/17_macros/macro2.lisp @@ -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 ): the symbol BOXED with the VALUE of X inside. +(defun wrap-value (x) + `(boxed x)) + +;; TODO: (add ): 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 '())) diff --git a/exercises/17_macros/macro3.lisp b/exercises/17_macros/macro3.lisp new file mode 100644 index 0000000..bc59f1e --- /dev/null +++ b/exercises/17_macros/macro3.lisp @@ -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))) diff --git a/exercises/17_macros/macro4.lisp b/exercises/17_macros/macro4.lisp new file mode 100644 index 0000000..6e2e77c --- /dev/null +++ b/exercises/17_macros/macro4.lisp @@ -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)) diff --git a/exercises/18_dynamic/README.md b/exercises/18_dynamic/README.md new file mode 100644 index 0000000..7495253 --- /dev/null +++ b/exercises/18_dynamic/README.md @@ -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. diff --git a/exercises/18_dynamic/dyn1.lisp b/exercises/18_dynamic/dyn1.lisp new file mode 100644 index 0000000..22cc766 --- /dev/null +++ b/exercises/18_dynamic/dyn1.lisp @@ -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))))) diff --git a/exercises/18_dynamic/dyn2.lisp b/exercises/18_dynamic/dyn2.lisp new file mode 100644 index 0000000..23efd94 --- /dev/null +++ b/exercises/18_dynamic/dyn2.lisp @@ -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))) diff --git a/exercises/18_dynamic/dyn3.lisp b/exercises/18_dynamic/dyn3.lisp new file mode 100644 index 0000000..683060b --- /dev/null +++ b/exercises/18_dynamic/dyn3.lisp @@ -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*)))))) diff --git a/exercises/quizzes/README.md b/exercises/quizzes/README.md new file mode 100644 index 0000000..9cca9ea --- /dev/null +++ b/exercises/quizzes/README.md @@ -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. diff --git a/exercises/quizzes/quiz1.lisp b/exercises/quizzes/quiz1.lisp new file mode 100644 index 0000000..8515e20 --- /dev/null +++ b/exercises/quizzes/quiz1.lisp @@ -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 " 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 " + (contact-card (find-contact *book* "ada"))) diff --git a/exercises/quizzes/quiz2.lisp b/exercises/quizzes/quiz2.lisp new file mode 100644 index 0000000..f13672c --- /dev/null +++ b/exercises/quizzes/quiz2.lisp @@ -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))) diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..1b51811 --- /dev/null +++ b/flake.lock @@ -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 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..0193362 --- /dev/null +++ b/flake.nix @@ -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"; + }; + }); + }; +} diff --git a/info.sexp b/info.sexp new file mode 100644 index 0000000..85f2010 --- /dev/null +++ b/info.sexp @@ -0,0 +1,240 @@ +;;; Lisplings exercise catalogue. +;;; +;;; Read by the lisplings runner. Each exercise is a plist: +;;; :name the exercise name; file is exercises//.lisp +;;; :dir the chapter directory +;;; :hint shown by `lisplings hint ' + +((: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.")))) diff --git a/lisplings b/lisplings new file mode 100755 index 0000000..3be5a24 --- /dev/null +++ b/lisplings @@ -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" "$@" diff --git a/nix/lisplings.sh b/nix/lisplings.sh new file mode 100644 index 0000000..c1918f9 --- /dev/null +++ b/nix/lisplings.sh @@ -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 "$@" diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..479b208 --- /dev/null +++ b/nix/package.nix @@ -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"; + }; +} diff --git a/solutions/00_intro/intro1.lisp b/solutions/00_intro/intro1.lisp new file mode 100644 index 0000000..dc6eb95 --- /dev/null +++ b/solutions/00_intro/intro1.lisp @@ -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.~%") diff --git a/solutions/00_intro/intro2.lisp b/solutions/00_intro/intro2.lisp new file mode 100644 index 0000000..6c3bead --- /dev/null +++ b/solutions/00_intro/intro2.lisp @@ -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.~%") diff --git a/solutions/01_sexps/sexps1.lisp b/solutions/01_sexps/sexps1.lisp new file mode 100644 index 0000000..97d3f0d --- /dev/null +++ b/solutions/01_sexps/sexps1.lisp @@ -0,0 +1,19 @@ +;;; S-EXPRESSIONS 1: PREFIX NOTATION (solution) + +(defun add-ten-and-thirty-two () + (+ 10 32)) + +(defun six-times-seven () + (* 6 7)) + +(defun fifty-from-one-hundred () + (- 100 50)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/01_sexps/sexps2.lisp b/solutions/01_sexps/sexps2.lisp new file mode 100644 index 0000000..28724b5 --- /dev/null +++ b/solutions/01_sexps/sexps2.lisp @@ -0,0 +1,19 @@ +;;; S-EXPRESSIONS 2: NESTING AND EXACT MATH (solution) + +(defun calc-a () + (* (+ 2 3) (- 4 1))) + +(defun calc-b () + (/ 100 (+ 2 3))) + +(defun one-half () + (/ 1 2)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/01_sexps/sexps3.lisp b/solutions/01_sexps/sexps3.lisp new file mode 100644 index 0000000..b8dc65f --- /dev/null +++ b/solutions/01_sexps/sexps3.lisp @@ -0,0 +1,19 @@ +;;; S-EXPRESSIONS 3: QUOTE (solution) + +(defun the-form () + '(+ 1 2)) + +(defun the-symbol () + 'hello) + +(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)) diff --git a/solutions/02_functions/functions1.lisp b/solutions/02_functions/functions1.lisp new file mode 100644 index 0000000..dab36fd --- /dev/null +++ b/solutions/02_functions/functions1.lisp @@ -0,0 +1,17 @@ +;;; FUNCTIONS 1: DEFUN (solution) + +(defun twice (x) + (* 2 x)) + +(defun add (a b) + (+ a b)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/02_functions/functions2.lisp b/solutions/02_functions/functions2.lisp new file mode 100644 index 0000000..42a6fb5 --- /dev/null +++ b/solutions/02_functions/functions2.lisp @@ -0,0 +1,17 @@ +;;; FUNCTIONS 2: ARITY AND ORDER (solution) + +(defun average (a b) + (/ (+ a b) 2)) + +(defun subtract (minuend subtrahend) + (- minuend subtrahend)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/02_functions/functions3.lisp b/solutions/02_functions/functions3.lisp new file mode 100644 index 0000000..a2019f6 --- /dev/null +++ b/solutions/02_functions/functions3.lisp @@ -0,0 +1,18 @@ +;;; FUNCTIONS 3: OPTIONAL AND KEYWORD ARGUMENTS (solution) + +(defun repeat-word (word &optional (n 2)) + (make-list n :initial-element word)) + +(defun make-box (width &key (height width) (depth width)) + (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)) diff --git a/solutions/02_functions/functions4.lisp b/solutions/02_functions/functions4.lisp new file mode 100644 index 0000000..5a22051 --- /dev/null +++ b/solutions/02_functions/functions4.lisp @@ -0,0 +1,16 @@ +;;; FUNCTIONS 4: MULTIPLE VALUES (solution) + +(defun divide (a b) + (floor a b)) + +(defun split-seconds (seconds) + (floor seconds 60)) + +;;; ------------------------------------------------------------------ +;;; 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))) diff --git a/solutions/03_variables/variables1.lisp b/solutions/03_variables/variables1.lisp new file mode 100644 index 0000000..4effb67 --- /dev/null +++ b/solutions/03_variables/variables1.lisp @@ -0,0 +1,14 @@ +;;; VARIABLES 1: GIVING A NAME TO A VALUE (solution) + +(defparameter *room-capacity* 100) + +(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))) diff --git a/solutions/03_variables/variables2.lisp b/solutions/03_variables/variables2.lisp new file mode 100644 index 0000000..af257f5 --- /dev/null +++ b/solutions/03_variables/variables2.lisp @@ -0,0 +1,18 @@ +;;; VARIABLES 2: LET AND SHADOWING (solution) + +(defun shadow-add () + (let ((x 15)) + (let ((x (+ x 5))) + x))) + +(defun wrap-me () + (let ((x 15)) + (+ 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)) diff --git a/solutions/03_variables/variables3.lisp b/solutions/03_variables/variables3.lisp new file mode 100644 index 0000000..05beb1f --- /dev/null +++ b/solutions/03_variables/variables3.lisp @@ -0,0 +1,13 @@ +;;; VARIABLES 3: LET AND LET* (solution) + +(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)) diff --git a/solutions/03_variables/variables4.lisp b/solutions/03_variables/variables4.lisp new file mode 100644 index 0000000..5b26bc1 --- /dev/null +++ b/solutions/03_variables/variables4.lisp @@ -0,0 +1,16 @@ +;;; VARIABLES 4: SETF ON PLACES (solution) + +(defparameter *account* (list :owner "Ada" :balance 100)) + +(defun deposit (amount) + (setf (getf *account* :balance) + (+ amount (getf *account* :balance))) + *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)) diff --git a/solutions/04_conditionals/if1.lisp b/solutions/04_conditionals/if1.lisp new file mode 100644 index 0000000..fb70682 --- /dev/null +++ b/solutions/04_conditionals/if1.lisp @@ -0,0 +1,15 @@ +;;; CONDITIONALS 1: IF (solution) + +(defun classify (temperature) + (if (> temperature 30) + "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)) diff --git a/solutions/04_conditionals/if2.lisp b/solutions/04_conditionals/if2.lisp new file mode 100644 index 0000000..a091be1 --- /dev/null +++ b/solutions/04_conditionals/if2.lisp @@ -0,0 +1,15 @@ +;;; CONDITIONALS 2: COND (solution) + +(defun describe-number (n) + (cond ((zerop n) "zero") + ((minusp n) "negative") + (t "positive"))) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/04_conditionals/if3.lisp b/solutions/04_conditionals/if3.lisp new file mode 100644 index 0000000..4fb93f8 --- /dev/null +++ b/solutions/04_conditionals/if3.lisp @@ -0,0 +1,18 @@ +;;; CONDITIONALS 3: WHEN AND UNLESS (solution) + +(defun only-positive-squares (n) + (when (plusp n) + (* n n))) + +(defun enter (door-open-p) + (if door-open-p :welcome :denied)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/04_conditionals/if4.lisp b/solutions/04_conditionals/if4.lisp new file mode 100644 index 0000000..0523f3d --- /dev/null +++ b/solutions/04_conditionals/if4.lisp @@ -0,0 +1,19 @@ +;;; CONDITIONALS 4: AND AND OR (solution) + +(defun first-truthy (a b c) + (or a b c)) + +(defun safe-div (a b) + (or (unless (zerop b) (/ a b)) + :undefined)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/05_predicates/pred1.lisp b/solutions/05_predicates/pred1.lisp new file mode 100644 index 0000000..a7c2899 --- /dev/null +++ b/solutions/05_predicates/pred1.lisp @@ -0,0 +1,14 @@ +;;; PREDICATES 1: WHAT IS TRUE? (solution) + +(defun truthy-p (thing) + (not (null 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 '()))) diff --git a/solutions/05_predicates/pred2.lisp b/solutions/05_predicates/pred2.lisp new file mode 100644 index 0000000..2530031 --- /dev/null +++ b/solutions/05_predicates/pred2.lisp @@ -0,0 +1,17 @@ +;;; PREDICATES 2: THE COMPARISON LADDER (solution) + +(defun same-list-p (a b) + (equal a b)) + +(defun same-number-p (a b) + (= 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))) diff --git a/solutions/05_predicates/pred3.lisp b/solutions/05_predicates/pred3.lisp new file mode 100644 index 0000000..0dd7969 --- /dev/null +++ b/solutions/05_predicates/pred3.lisp @@ -0,0 +1,18 @@ +;;; PREDICATES 3: ASKING ABOUT TYPES (solution) + +(defun describe-value (v) + (cond ((null v) :nothing) + ((numberp v) :number) + ((stringp v) :string) + ((listp v) :list) + (t :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)) diff --git a/solutions/06_lists/lists1.lisp b/solutions/06_lists/lists1.lisp new file mode 100644 index 0000000..0b79177 --- /dev/null +++ b/solutions/06_lists/lists1.lisp @@ -0,0 +1,20 @@ +;;; LISTS 1: CONS, CAR, CDR (solution) + +(defun first-of (xs) + (car xs)) + +(defun rest-of (xs) + (cdr xs)) + +(defun prepend (x xs) + (cons 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)) diff --git a/solutions/06_lists/lists2.lisp b/solutions/06_lists/lists2.lisp new file mode 100644 index 0000000..fdc3e23 --- /dev/null +++ b/solutions/06_lists/lists2.lisp @@ -0,0 +1,19 @@ +;;; LISTS 2: LIST, QUOTE, AND APPEND (solution) + +(defun abc () + '(a b c)) + +(defun one-two-three () + (list 1 2 3)) + +(defun joined () + (append '(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)) diff --git a/solutions/06_lists/lists3.lisp b/solutions/06_lists/lists3.lisp new file mode 100644 index 0000000..445be70 --- /dev/null +++ b/solutions/06_lists/lists3.lisp @@ -0,0 +1,20 @@ +;;; LISTS 3: ELEMENTS BY POSITION (solution) + +(defun my-first (xs) + (nth 0 xs)) + +(defun my-last (xs) + (car (last xs))) + +(defun drop-last (xs) + (butlast 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))) diff --git a/solutions/06_lists/lists4.lisp b/solutions/06_lists/lists4.lisp new file mode 100644 index 0000000..aae1426 --- /dev/null +++ b/solutions/06_lists/lists4.lisp @@ -0,0 +1,21 @@ +;;; LISTS 4: PUSH AND POP (solution) + +(defun push-two (xs) + (let ((ys xs)) + (push 0 ys) + (push 1 ys) + ys)) + +(defun skip-two (xs) + (let ((ys xs)) + (pop ys) + (pop ys) + 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))) diff --git a/solutions/06_lists/lists5.lisp b/solutions/06_lists/lists5.lisp new file mode 100644 index 0000000..97d72f9 --- /dev/null +++ b/solutions/06_lists/lists5.lisp @@ -0,0 +1,23 @@ +;;; LISTS 5: ASSOCIATION LISTS (solution) + +(defparameter *menu* + '((coffee . 3) (tea . 2) (cocoa . 4))) + +(defun price (item) + (cdr (assoc item *menu*))) + +(defun add-item (item cost) + (push (cons item cost) *menu*) + *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))))) diff --git a/solutions/07_recursion/recurs1.lisp b/solutions/07_recursion/recurs1.lisp new file mode 100644 index 0000000..c9d9889 --- /dev/null +++ b/solutions/07_recursion/recurs1.lisp @@ -0,0 +1,15 @@ +;;; RECURSION 1: SUMMING A LIST (solution) + +(defun sum (xs) + (if (null xs) + 0 + (+ (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))) diff --git a/solutions/07_recursion/recurs2.lisp b/solutions/07_recursion/recurs2.lisp new file mode 100644 index 0000000..0bfd02a --- /dev/null +++ b/solutions/07_recursion/recurs2.lisp @@ -0,0 +1,15 @@ +;;; RECURSION 2: LENGTH (solution) + +(defun my-length (xs) + (if (null xs) + 0 + (+ 1 (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))) diff --git a/solutions/07_recursion/recurs3.lisp b/solutions/07_recursion/recurs3.lisp new file mode 100644 index 0000000..0295a2c --- /dev/null +++ b/solutions/07_recursion/recurs3.lisp @@ -0,0 +1,15 @@ +;;; RECURSION 3: MEMBERSHIP (solution) + +(defun my-member (x xs) + (cond ((null xs) nil) + ((equal x (car xs)) xs) + (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))) diff --git a/solutions/07_recursion/recurs4.lisp b/solutions/07_recursion/recurs4.lisp new file mode 100644 index 0000000..d111af2 --- /dev/null +++ b/solutions/07_recursion/recurs4.lisp @@ -0,0 +1,17 @@ +;;; RECURSION 4: WALKING A TREE (solution) + +(defun count-leaves (tree) + (cond ((null tree) 0) + ((atom tree) 1) + (t (+ (count-leaves (car tree)) + (count-leaves (cdr 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)))) diff --git a/solutions/08_functional/func1.lisp b/solutions/08_functional/func1.lisp new file mode 100644 index 0000000..4902b43 --- /dev/null +++ b/solutions/08_functional/func1.lisp @@ -0,0 +1,17 @@ +;;; FUNCTIONAL 1: LAMBDA AND FUNCALL (solution) + +(defun apply-to-ten (f) + (funcall f 10)) + +(defun doubler () + (lambda (x) (* 2 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)) diff --git a/solutions/08_functional/func2.lisp b/solutions/08_functional/func2.lisp new file mode 100644 index 0000000..78fcc52 --- /dev/null +++ b/solutions/08_functional/func2.lisp @@ -0,0 +1,16 @@ +;;; FUNCTIONAL 2: MAPCAR (solution) + +(defun double-all (xs) + (mapcar (lambda (x) (* 2 x)) xs)) + +(defun shout-names (names) + (mapcar #'string-upcase 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"))) diff --git a/solutions/08_functional/func3.lisp b/solutions/08_functional/func3.lisp new file mode 100644 index 0000000..af039dd --- /dev/null +++ b/solutions/08_functional/func3.lisp @@ -0,0 +1,17 @@ +;;; FUNCTIONAL 3: FUNCALL AND APPLY (solution) + +(defun sum-of (xs) + (apply #'+ xs)) + +(defun call-with-more (f a xs) + (apply f a xs)) + +;;; ------------------------------------------------------------------ +;;; 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))) diff --git a/solutions/08_functional/func4.lisp b/solutions/08_functional/func4.lisp new file mode 100644 index 0000000..9ae0433 --- /dev/null +++ b/solutions/08_functional/func4.lisp @@ -0,0 +1,18 @@ +;;; FUNCTIONAL 4: REDUCE (solution) + +(defun biggest (xs) + (reduce #'max xs)) + +(defun product (xs) + (reduce #'* xs :initial-value 1)) + +;;; ------------------------------------------------------------------ +;;; 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 '())) diff --git a/solutions/09_strings/str1.lisp b/solutions/09_strings/str1.lisp new file mode 100644 index 0000000..8a71217 --- /dev/null +++ b/solutions/09_strings/str1.lisp @@ -0,0 +1,17 @@ +;;; STRINGS 1: FORMAT DIRECTIVES (solution) + +(defun cats (name count) + (format nil "~a has ~a cats." name count)) + +(defun banner (name) + (format nil "~10a!" 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")) diff --git a/solutions/09_strings/str2.lisp b/solutions/09_strings/str2.lisp new file mode 100644 index 0000000..cc406ff --- /dev/null +++ b/solutions/09_strings/str2.lisp @@ -0,0 +1,21 @@ +;;; STRINGS 2: THE STRING TOOLBOX (solution) + +(defun first-three (s) + (subseq s 0 3)) + +(defun shout (s) + (concatenate 'string (string-upcase s) "!!")) + +(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")) diff --git a/solutions/09_strings/str3.lisp b/solutions/09_strings/str3.lisp new file mode 100644 index 0000000..4b779d1 --- /dev/null +++ b/solutions/09_strings/str3.lisp @@ -0,0 +1,17 @@ +;;; STRINGS 3: JOINING AND COMPARING (solution) + +(defun full-name (first last) + (concatenate 'string first " " last)) + +(defun same-name-p (first last) + (string-equal 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"))) diff --git a/solutions/09_strings/str4.lisp b/solutions/09_strings/str4.lisp new file mode 100644 index 0000000..6a829d1 --- /dev/null +++ b/solutions/09_strings/str4.lisp @@ -0,0 +1,17 @@ +;;; STRINGS 4: FORMAT ITERATION (solution) + +(defun comma-list (xs) + (format nil "~{~a~^, ~}" xs)) + +(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"))) diff --git a/solutions/10_loops/loops1.lisp b/solutions/10_loops/loops1.lisp new file mode 100644 index 0000000..f94afdb --- /dev/null +++ b/solutions/10_loops/loops1.lisp @@ -0,0 +1,23 @@ +;;; LOOPS 1: DOLIST AND DOTIMES (solution) + +(defun sum-of (xs) + (let ((total 0)) + (dolist (x xs) + (incf total x)) + total)) + +(defun countdown (n) + (let ((acc '())) + (dotimes (i n) + (push i 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)) diff --git a/solutions/10_loops/loops2.lisp b/solutions/10_loops/loops2.lisp new file mode 100644 index 0000000..76bcdf3 --- /dev/null +++ b/solutions/10_loops/loops2.lisp @@ -0,0 +1,19 @@ +;;; LOOPS 2: THE LOOP MACRO (solution) + +(defun squares (xs) + (loop for x in xs + collect (* x x))) + +(defun triangle (n) + (loop for i from 1 to n + sum 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)) diff --git a/solutions/10_loops/loops3.lisp b/solutions/10_loops/loops3.lisp new file mode 100644 index 0000000..359c9f6 --- /dev/null +++ b/solutions/10_loops/loops3.lisp @@ -0,0 +1,20 @@ +;;; LOOPS 3: LOOP WITH TESTS (solution) + +(defun evens (xs) + (loop for x in xs + when (evenp x) + collect x)) + +(defun first-big (xs) + (loop for x in xs + thereis (if (> x 100) 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))) diff --git a/solutions/11_numbers/num1.lisp b/solutions/11_numbers/num1.lisp new file mode 100644 index 0000000..d59f897 --- /dev/null +++ b/solutions/11_numbers/num1.lisp @@ -0,0 +1,15 @@ +;;; NUMBERS 1: THE TOWER (solution) + +(defun two-to-the-hundred () + (expt 2 100)) + +(defun half-of-seven () + (/ 7 2)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/11_numbers/num2.lisp b/solutions/11_numbers/num2.lisp new file mode 100644 index 0000000..60c85e6 --- /dev/null +++ b/solutions/11_numbers/num2.lisp @@ -0,0 +1,19 @@ +;;; NUMBERS 2: ROUNDING AND REMAINDERS (solution) + +(defun floor-to-five (x) + (* 5 (floor x 5))) + +(defun mod-five (x) + (mod 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)) diff --git a/solutions/11_numbers/num3.lisp b/solutions/11_numbers/num3.lisp new file mode 100644 index 0000000..2265e35 --- /dev/null +++ b/solutions/11_numbers/num3.lisp @@ -0,0 +1,27 @@ +;;; NUMBERS 3: BOUNDS AND STEPS (solution) + +(defun clamp (x low high) + (min high (max low x))) + +(defun distance-1d (a b) + (abs (- a b))) + +(defun walk () + (let ((n 10)) + (incf n) + (decf n 2) + (incf n 5) + 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)) diff --git a/solutions/12_structs/structs1.lisp b/solutions/12_structs/structs1.lisp new file mode 100644 index 0000000..26b8e16 --- /dev/null +++ b/solutions/12_structs/structs1.lisp @@ -0,0 +1,21 @@ +;;; STRUCTS 1: DEFSTRUCT (solution) + +(defstruct person + name + age) + +(defun make-ada () + (make-person :name "Ada" :age 36)) + +(defun ada-age (ada) + (person-age 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)))) diff --git a/solutions/12_structs/structs2.lisp b/solutions/12_structs/structs2.lisp new file mode 100644 index 0000000..828cb44 --- /dev/null +++ b/solutions/12_structs/structs2.lisp @@ -0,0 +1,23 @@ +;;; STRUCTS 2: DEFAULTS AND PREDICATES (solution) + +(defstruct spaceship + (name "unnamed") + (crew-size 1)) + +(defun seven-crew () + (make-spaceship :crew-size 7)) + +(defun ship-p (x) + (spaceship-p x)) + +;;; ------------------------------------------------------------------ +;;; 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)))) diff --git a/solutions/12_structs/structs3.lisp b/solutions/12_structs/structs3.lisp new file mode 100644 index 0000000..c63412d --- /dev/null +++ b/solutions/12_structs/structs3.lisp @@ -0,0 +1,24 @@ +;;; STRUCTS 3: MUTATION (solution) + +(defstruct counter + (value 0)) + +(defun bump (c) + (incf (counter-value c)) + c) + +(defun reset-counter (c) + (setf (counter-value c) 0) + 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)))) diff --git a/solutions/12_structs/structs4.lisp b/solutions/12_structs/structs4.lisp new file mode 100644 index 0000000..b0bd7d4 --- /dev/null +++ b/solutions/12_structs/structs4.lisp @@ -0,0 +1,24 @@ +;;; STRUCTS 4: INHERITANCE (solution) + +(defstruct person + name + age) + +(defstruct (student (:include person)) + major) + +(defun make-zed () + (make-student :name "Zed" :age 21 :major "physics")) + +(defun zed-major (zed) + (student-major 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))))) diff --git a/solutions/13_hash_tables/hash1.lisp b/solutions/13_hash_tables/hash1.lisp new file mode 100644 index 0000000..4bdd9ac --- /dev/null +++ b/solutions/13_hash_tables/hash1.lisp @@ -0,0 +1,20 @@ +;;; HASH TABLES 1: BASICS (solution) + +(defun people () + (let ((table (make-hash-table))) + (setf (gethash 'ada table) 36 + (gethash 'grace table) 45) + table)) + +(defun age-of (name table) + (gethash name table)) + +;;; ------------------------------------------------------------------ +;;; 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))))) diff --git a/solutions/13_hash_tables/hash2.lisp b/solutions/13_hash_tables/hash2.lisp new file mode 100644 index 0000000..ac2aecb --- /dev/null +++ b/solutions/13_hash_tables/hash2.lisp @@ -0,0 +1,25 @@ +;;; HASH TABLES 2: IS THE KEY THERE? (solution) + +(defun has-key-p (key table) + (nth-value 1 (gethash key table))) + +(defun lookup (key table default) + (multiple-value-bind (value present) + (gethash key table) + (if present value default))) + +;;; ------------------------------------------------------------------ +;;; 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))))) diff --git a/solutions/13_hash_tables/hash3.lisp b/solutions/13_hash_tables/hash3.lisp new file mode 100644 index 0000000..55821a5 --- /dev/null +++ b/solutions/13_hash_tables/hash3.lisp @@ -0,0 +1,18 @@ +;;; HASH TABLES 3: COUNTING (solution) + +(defun tally (xs) + (let ((table (make-hash-table))) + (dolist (x xs) + (incf (gethash x table 0))) + 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))))) diff --git a/solutions/14_packages/pkg1.lisp b/solutions/14_packages/pkg1.lisp new file mode 100644 index 0000000..6277352 --- /dev/null +++ b/solutions/14_packages/pkg1.lisp @@ -0,0 +1,20 @@ +;;; PACKAGES 1: DEFPACKAGE (solution) + +(defpackage #:shapes + (:use #:common-lisp) + (:export #:area)) + +(in-package #:shapes) + +(defun area (s) + (* s s)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/14_packages/pkg2.lisp b/solutions/14_packages/pkg2.lisp new file mode 100644 index 0000000..a9fb7a0 --- /dev/null +++ b/solutions/14_packages/pkg2.lisp @@ -0,0 +1,19 @@ +;;; PACKAGES 2: EXPORTS (solution) + +(defpackage #:kitchen + (:use #:common-lisp) + (:export #:make-soup)) + +(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)) diff --git a/solutions/14_packages/pkg3.lisp b/solutions/14_packages/pkg3.lisp new file mode 100644 index 0000000..a5add66 --- /dev/null +++ b/solutions/14_packages/pkg3.lisp @@ -0,0 +1,29 @@ +;;; PACKAGES 3: USING ANOTHER PACKAGE (solution) + +(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) + +(defun total (a b) + (+ (area a) (area b))) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/15_clos/clos1.lisp b/solutions/15_clos/clos1.lisp new file mode 100644 index 0000000..9273ab5 --- /dev/null +++ b/solutions/15_clos/clos1.lisp @@ -0,0 +1,17 @@ +;;; CLOS 1: CLASSES AND INSTANCES (solution) + +(defclass dog () + ((name :initarg :name :accessor dog-name) + (tricks :initarg :tricks :accessor dog-tricks :initform '()))) + +(defun make-rex () + (make-instance 'dog :name "Rex" :tricks '("sit" "roll-over"))) + +;;; ------------------------------------------------------------------ +;;; 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))))) diff --git a/solutions/15_clos/clos2.lisp b/solutions/15_clos/clos2.lisp new file mode 100644 index 0000000..cbf5863 --- /dev/null +++ b/solutions/15_clos/clos2.lisp @@ -0,0 +1,20 @@ +;;; CLOS 2: GENERIC FUNCTIONS (solution) + +(defclass animal () ()) +(defclass dog (animal) ()) +(defclass cat (animal) ()) + +(defgeneric speak (a)) + +(defmethod speak ((a dog)) "woof") +(defmethod speak ((a cat)) "meow") +(defmethod speak ((a animal)) "...") + +;;; ------------------------------------------------------------------ +;;; 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))) diff --git a/solutions/15_clos/clos3.lisp b/solutions/15_clos/clos3.lisp new file mode 100644 index 0000000..d17e47d --- /dev/null +++ b/solutions/15_clos/clos3.lisp @@ -0,0 +1,27 @@ +;;; CLOS 3: COMBINING METHODS (solution) + +(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))) + +(defmethod deposit :after ((a account) amount) + (push (list 'deposited 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))))) diff --git a/solutions/15_clos/clos4.lisp b/solutions/15_clos/clos4.lisp new file mode 100644 index 0000000..2287d60 --- /dev/null +++ b/solutions/15_clos/clos4.lisp @@ -0,0 +1,17 @@ +;;; CLOS 4: DISPATCH ON A VALUE (solution) + +(defgeneric serve (customer)) + +(defmethod serve (customer) + "one espresso") + +(defmethod serve ((customer (eql 'vip))) + "a free muffin too") + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/16_conditions/cond1.lisp b/solutions/16_conditions/cond1.lisp new file mode 100644 index 0000000..1e8941a --- /dev/null +++ b/solutions/16_conditions/cond1.lisp @@ -0,0 +1,14 @@ +;;; CONDITIONS 1: ERROR AND HANDLER-CASE (solution) + +(defun safe-parse (string) + (handler-case (parse-integer string) + (parse-error () :not-a-number))) + +;;; ------------------------------------------------------------------ +;;; 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")) diff --git a/solutions/16_conditions/cond2.lisp b/solutions/16_conditions/cond2.lisp new file mode 100644 index 0000000..cf74d8b --- /dev/null +++ b/solutions/16_conditions/cond2.lisp @@ -0,0 +1,22 @@ +;;; CONDITIONS 2: UNWIND-PROTECT (solution) + +(defparameter *lid* :closed) + +(defun with-lid (f) + (unwind-protect + (progn (setf *lid* :open) + (funcall f)) + (setf *lid* :closed))) + +;;; ------------------------------------------------------------------ +;;; 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*)) diff --git a/solutions/16_conditions/cond3.lisp b/solutions/16_conditions/cond3.lisp new file mode 100644 index 0000000..2a6b740 --- /dev/null +++ b/solutions/16_conditions/cond3.lisp @@ -0,0 +1,22 @@ +;;; CONDITIONS 3: YOUR OWN CONDITION TYPES (solution) + +(define-condition empty-plate (error) + ((what :initarg :what :reader empty-plate-what)) + (:documentation "Signaled when a plate turns out to be empty.")) + +(defun eat (xs) + (if (null xs) + (error 'empty-plate :what "soup") + "yum")) + +(defun catch-empty (xs) + (handler-case (eat xs) + (empty-plate (e) (empty-plate-what e)))) + +;;; ------------------------------------------------------------------ +;;; 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 '())) diff --git a/solutions/16_conditions/cond4.lisp b/solutions/16_conditions/cond4.lisp new file mode 100644 index 0000000..2f38b8d --- /dev/null +++ b/solutions/16_conditions/cond4.lisp @@ -0,0 +1,23 @@ +;;; CONDITIONS 4: RESTARTS (solution) + +(defun safe-car (xs) + (restart-case + (if (consp xs) + (car xs) + (error "safe-car: ~s is not a cons" xs)) + (use-nil () nil))) + +(defun car-with-default (xs) + (handler-bind ((error (lambda (e) + (declare (ignore e)) + (invoke-restart 'use-nil)))) + (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)) diff --git a/solutions/17_macros/macro1.lisp b/solutions/17_macros/macro1.lisp new file mode 100644 index 0000000..d1f5b97 --- /dev/null +++ b/solutions/17_macros/macro1.lisp @@ -0,0 +1,13 @@ +;;; MACROS 1: DEFMACRO (solution) + +(defmacro my-when (test &body body) + `(if ,test (progn ,@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)) diff --git a/solutions/17_macros/macro2.lisp b/solutions/17_macros/macro2.lisp new file mode 100644 index 0000000..3f15748 --- /dev/null +++ b/solutions/17_macros/macro2.lisp @@ -0,0 +1,16 @@ +;;; MACROS 2: BACKQUOTE, COMMA, SPLICE (solution) + +(defun wrap-value (x) + `(boxed ,x)) + +(defun make-add-form (numbers) + `(add ,@numbers)) + +;;; ------------------------------------------------------------------ +;;; 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 '())) diff --git a/solutions/17_macros/macro3.lisp b/solutions/17_macros/macro3.lisp new file mode 100644 index 0000000..8ae2bde --- /dev/null +++ b/solutions/17_macros/macro3.lisp @@ -0,0 +1,16 @@ +;;; MACROS 3: GENSYM AND HYGIENE (solution) + +(defmacro n-plus-five (n) + (let ((temp (gensym))) + `(let ((,temp 5)) + (+ ,n ,temp)))) + +;;; ------------------------------------------------------------------ +;;; 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))) diff --git a/solutions/17_macros/macro4.lisp b/solutions/17_macros/macro4.lisp new file mode 100644 index 0000000..f982222 --- /dev/null +++ b/solutions/17_macros/macro4.lisp @@ -0,0 +1,18 @@ +;;; MACROS 4: A MACRO OF YOUR OWN (solution) + +(defmacro while (test &body body) + `(loop while ,test do ,@body)) + +;;; ------------------------------------------------------------------ +;;; 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)) diff --git a/solutions/18_dynamic/dyn1.lisp b/solutions/18_dynamic/dyn1.lisp new file mode 100644 index 0000000..9387ccb --- /dev/null +++ b/solutions/18_dynamic/dyn1.lisp @@ -0,0 +1,15 @@ +;;; DYNAMIC 1: CLOSURES (solution) + +(defun make-counter () + (let ((count 0)) + (lambda () (incf 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))))) diff --git a/solutions/18_dynamic/dyn2.lisp b/solutions/18_dynamic/dyn2.lisp new file mode 100644 index 0000000..95d2878 --- /dev/null +++ b/solutions/18_dynamic/dyn2.lisp @@ -0,0 +1,20 @@ +;;; DYNAMIC 2: SPECIAL VARIABLES (solution) + +(defparameter *depth* 0) + +(defun current-depth () + *depth*) + +(defun with-depth (n f) + (let ((*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))) diff --git a/solutions/18_dynamic/dyn3.lisp b/solutions/18_dynamic/dyn3.lisp new file mode 100644 index 0000000..2b49c04 --- /dev/null +++ b/solutions/18_dynamic/dyn3.lisp @@ -0,0 +1,29 @@ +;;; DYNAMIC 3: A MEMOIZING CLOSURE (solution) + +(defparameter *fib-calls* 0) + +(defun slow-fib (n) + (incf *fib-calls*) + (if (< n 2) + n + (+ (slow-fib (- n 1)) (slow-fib (- n 2))))) + +(defun make-memo-fib () + (let ((table (make-hash-table))) + (lambda (n) + (multiple-value-bind (value present) (gethash n table) + (if present + value + (setf (gethash n table) (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*)))))) diff --git a/solutions/quizzes/quiz1.lisp b/solutions/quizzes/quiz1.lisp new file mode 100644 index 0000000..28059ef --- /dev/null +++ b/solutions/quizzes/quiz1.lisp @@ -0,0 +1,32 @@ +;;; QUIZ 1: THE CONTACT BOOK (solution) + +(defparameter *book* + (list (list :name "Ada" :email "ada@example.com") + (list :name "Grace" :email "grace@example.com"))) + +(defun add-contact (book name email) + (append book (list (list :name name :email email)))) + +(defun find-contact (book name) + (dolist (contact book) + (when (string-equal name (getf contact :name)) + (return contact)))) + +(defun contact-card (contact) + (format nil "~a <~a>" (getf contact :name) (getf contact :email))) + +;;; ------------------------------------------------------------------ +;;; 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 " + (contact-card (find-contact *book* "ada"))) diff --git a/solutions/quizzes/quiz2.lisp b/solutions/quizzes/quiz2.lisp new file mode 100644 index 0000000..9aa5708 --- /dev/null +++ b/solutions/quizzes/quiz2.lisp @@ -0,0 +1,22 @@ +;;; QUIZ 2: A TINY LISP, IN LISP (solution) + +(defun eval-expr (expr) + (cond ((numberp expr) expr) + ((and (consp expr) (eq 'quote (car expr))) + (second expr)) + ((and (consp expr) (member (car expr) '(+ - *))) + (apply (car expr) (mapcar #'eval-expr (cdr expr)))) + (t (error "cannot evaluate ~s" 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))) diff --git a/src/core.lisp b/src/core.lisp new file mode 100644 index 0000000..1ad7b0f --- /dev/null +++ b/src/core.lisp @@ -0,0 +1,494 @@ +;;;; Lisplings: small exercises to get you used to reading and +;;;; writing Common Lisp code. +;;;; +;;;; core.lisp: exercise catalogue, progress state, and all commands. + +(defpackage #:lisplings + (:use #:common-lisp) + (:export #:main)) +(in-package #:lisplings) + +;;; --------------------------------------------------------------------- +;;; Globals and pathnames + +(defparameter *sbcl-bin* + (or (sb-ext:posix-getenv "LISPLINGS_SBCL") + (ignore-errors (namestring (truename sb-ext:*runtime-pathname*))) + "sbcl")) + +(defparameter *source-root* + ;; The lisplings source checkout: the parent directory of src/. + (make-pathname :directory (butlast (pathname-directory (truename *load-truename*))))) + +(defparameter *project* nil) ; directory to operate on +(defparameter *info* nil) ; parsed info.sexp +(defparameter *exercises* nil) ; list of exercise structs +(defparameter *state* nil) ; (:done ("name" ...) :current "name") + +(defstruct exercise + name dir hint done path solution-path) + +(defun info-field (key) + (second (assoc key *info*))) + +(defun cwd-directory () + (let ((cwd (ignore-errors (sb-posix:getcwd)))) + (if (and cwd (plusp (length cwd))) + (pathname (if (char= #\/ (char cwd (1- (length cwd)))) + cwd + (concatenate 'string cwd "/"))) + *default-pathname-defaults*))) + +(defun project-p (dir) + (and dir + (probe-file (merge-pathnames "info.sexp" dir)) + (probe-file (merge-pathnames "exercises/" dir)) + dir)) + +(defun detect-project () + (or (project-p (cwd-directory)) + (project-p *source-root*) + (error "This is not a lisplings project.~%Run lisplings inside a lisplings checkout, or create one first:~% lisplings init my-lisplings~%then start it from inside that directory."))) + +(defun setup () + (setf *project* (detect-project) + *info* (with-open-file (in (merge-pathnames "info.sexp" *project*)) + (read in)) + *state* (load-state) + *exercises* (make-exercises)) + (unless (plusp (length *exercises*)) + (error "The exercise catalogue (info.sexp) is empty."))) + +(defun make-exercises () + (mapcar (lambda (spec) + (let ((name (getf spec :name)) + (dir (getf spec :dir))) + (make-exercise + :name name + :dir dir + :hint (getf spec :hint) + :done (and (member name (getf *state* :done) :test #'string=) t) + :path (merge-pathnames (format nil "exercises/~a/~a.lisp" dir name) + *project*) + :solution-path (merge-pathnames (format nil "solutions/~a/~a.lisp" dir name) + *project*)))) + (info-field :exercises))) + +(defun find-exercise (name) + (or (find name *exercises* :key #'exercise-name :test #'string=) + (error "No exercise named ~s. Try `lisplings list'." name))) + +;;; --------------------------------------------------------------------- +;;; Progress state + +(defun state-path () + (merge-pathnames ".lisplings-state.sexp" *project*)) + +(defun load-state () + (or (ignore-errors + (with-open-file (in (state-path)) + (let ((state (read in))) + (when (listp state) state)))) + '(:done nil :current nil))) + +(defun save-state () + (with-open-file (out (state-path) :direction :output + :if-exists :supersede :if-does-not-exist :create) + (with-standard-io-syntax + (format out "~s~%" *state*)))) + +(defun mark-done (ex) + (setf (exercise-done ex) t) + (pushnew (exercise-name ex) (getf *state* :done) :test #'string=) + (save-state)) + +(defun unmark-done (ex) + (setf (exercise-done ex) nil) + (setf (getf *state* :done) + (remove (exercise-name ex) (getf *state* :done) :test #'string=)) + (save-state)) + +(defun set-current-name (name) + (setf (getf *state* :current) name) + (save-state)) + +;;; --------------------------------------------------------------------- +;;; Pristine copies, so `reset' can undo any experiment + +(defun copy-file (from to) + (ensure-directories-exist to) + (with-open-file (in from :element-type '(unsigned-byte 8)) + (with-open-file (out to :element-type '(unsigned-byte 8) + :direction :output :if-exists :supersede) + (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) + (loop for n = (read-sequence buffer in) + until (zerop n) + do (write-sequence buffer out :end n)))))) + +(defun orig-root () + (merge-pathnames ".lisplings-orig/" *project*)) + +(defun orig-path (ex) + (merge-pathnames (format nil "~a/~a.lisp" (exercise-dir ex) (exercise-name ex)) + (orig-root))) + +(defun ensure-orig-snapshot () + "Snapshot the pristine exercises the first time lisplings runs here, +so `reset' can restore them. Start lisplings before editing anything!" + (let ((orig (orig-root))) + (unless (probe-file orig) + (dolist (ex *exercises*) + (copy-file (exercise-path ex) (orig-path ex))) + (format *error-output* + "~&Snapshotted pristine exercises to .lisplings-orig/ (this is what `reset' restores).~%")))) + +;;; --------------------------------------------------------------------- +;;; Terminal helpers + +(defparameter *use-color* + (and (not (or (sb-ext:posix-getenv "NO_COLOR") + (sb-ext:posix-getenv "LISPLINGS_NO_COLOR"))) + (sb-ext:posix-getenv "TERM") + (not (string= "dumb" (sb-ext:posix-getenv "TERM"))))) + +(defun ansi (code string) + (if *use-color* + (format nil "~c[~dm~a~c[0m" #\escape code string #\escape) + string)) + +(defun red (s) (ansi 31 s)) +(defun green (s) (ansi 32 s)) +(defun yellow (s) (ansi 33 s)) +(defun bold (s) (ansi 1 s)) + +(defun stdout-is-tty-p () + (ignore-errors (plusp (sb-unix:unix-isatty 1)))) + +(defun clear-screen () + (when (stdout-is-tty-p) + (format t "~c[H~c[2J~c[3J" #\escape #\escape #\escape) + (finish-output))) + +(defun progress-bar () + (let* ((total (length *exercises*)) + (done (count-if #'exercise-done *exercises*)) + (width 28) + (filled (if (zerop total) 0 (floor (* width done) total)))) + (format nil "[~a~a] ~d% (~d/~d done)" + (make-string filled :initial-element #\#) + (make-string (- width filled) :initial-element #\-) + (floor (* 100 done) (max 1 total)) + done total))) + +;;; --------------------------------------------------------------------- +;;; Running exercises + +(defun exercise-mtime (ex) + (ignore-errors (file-write-date (exercise-path ex)))) + +(defun run-exercise-file (path &key (timeout 60)) + "Run the exercise at PATH in a fresh SBCL subprocess. +Returns (values output-string exit-code timed-out-p)." + (let* ((runner (merge-pathnames "src/exercise-runner.lisp" *source-root*)) + (proc (sb-ext:run-program *sbcl-bin* + (list "--noinform" "--no-sysinit" "--no-userinit" + "--disable-debugger" "--script" + (namestring runner) + (namestring path)) + :wait nil :input nil :search t + :output :stream :error :output)) + (timed-out nil) + (killer (sb-thread:make-thread + (lambda () + (do ((i 0 (+ i 1))) + ((or (>= i (* 10 (max 1 timeout))) + (not (eq :running (sb-ext:process-status proc))))) + (sleep 0.1)) + (when (eq :running (sb-ext:process-status proc)) + (setf timed-out t) + (ignore-errors (sb-ext:process-kill proc 9)))) + :name "lisplings-killer")) + (output (with-output-to-string (out) + (let ((stream (sb-ext:process-output proc))) + (handler-case + (loop for line = (read-line stream nil :eof) + until (eq line :eof) + do (write-line line out)) + (error () nil)))))) + (sb-ext:process-wait proc) + (sb-thread:join-thread killer) + (values output (sb-ext:process-exit-code proc) timed-out))) + +(defun run-and-show (ex) + (clear-screen) + (format t "~&~a~%" (bold (format nil "Lisplings · ~a" (exercise-name ex)))) + (format t "~&Editing: ~a~%~%" (namestring (exercise-path ex))) + (finish-output) + (multiple-value-bind (output code timed-out-p) + (run-exercise-file (exercise-path ex)) + (format t "~a~%" output) + (cond + (timed-out-p + (format t "~&~a~%~%" (red "Timed out after 60 seconds. Infinite loop? Check the base case, or type r to rerun."))) + ((zerop code) + (mark-done ex) + (format t "~&~a~%~%" (green "Solved! Press n for the next exercise."))) + (t + (format t "~&~a~%~%" (red "Keep working; the checks rerun every time you save.")))) + (format t "~&~a~%~%" (progress-bar)) + (format t "n next · h hint · r rerun · l list · q quit~%") + (finish-output))) + +;;; --------------------------------------------------------------------- +;;; Watch mode + +(defun show-welcome () + (clear-screen) + (format t "~a~%~%" (info-field :welcome)) + (format t "Press ENTER to start ") + (finish-output) + (read-line *standard-input* nil nil) + (clear-screen)) + +(defun show-hint (ex) + (format t "~&~a~%" (yellow (format nil "Hint for ~a:" (exercise-name ex)))) + (format t "~&~a~%~%" (or (exercise-hint ex) + "No hint for this one. You're on your own!")) + (finish-output)) + +(defun list-exercises (filter) + (format t "~&~a~%" (bold "Lisplings exercises:")) + (dolist (ex *exercises*) + (when (ecase filter + (:all t) + (:pending (not (exercise-done ex))) + (:done (exercise-done ex))) + (format t " ~a ~a~%" + (if (exercise-done ex) (green "✓ ") (yellow ". ")) + (format nil "~a/~a" (exercise-dir ex) (exercise-name ex))))) + (format t "~&~%Pending: ~d of ~d. Progress: ~a~%~%" + (count-if (complement #'exercise-done) *exercises*) + (length *exercises*) + (progress-bar)) + (finish-output)) + +(defun initial-index () + (or (let ((name (getf *state* :current))) + (and name + (position-if (lambda (ex) (string= name (exercise-name ex))) + *exercises*))) + (position-if (complement #'exercise-done) *exercises*) + (1- (length *exercises*)))) + +(defun next-pending-index (from) + (position-if (complement #'exercise-done) *exercises* + :start (1+ from))) + +(defun pop-command (queue lock) + (sb-thread:with-mutex (lock) + (pop (car queue)))) + +(defun watch () + (ensure-orig-snapshot) + (unless (probe-file (state-path)) + (show-welcome)) + (let* ((queue (list nil)) + (lock (sb-thread:make-mutex)) + (stdin *standard-input*) + (reader (sb-thread:make-thread + (lambda () + (ignore-errors + (loop for line = (read-line stdin nil :eof) + until (eq line :eof) + do (sb-thread:with-mutex (lock) + (setf (car queue) + (append (car queue) + (list (string-trim " " line)))))))) + :name "lisplings-input"))) + (declare (ignore reader)) + (let ((index (initial-index))) + (set-current-name (exercise-name (nth index *exercises*))) + (run-and-show (nth index *exercises*)) + (block watch-loop + (loop + (loop for cmd = (pop-command queue lock) + while cmd + do (cond + ((string-equal cmd "n") + (let ((current (nth index *exercises*))) + (cond ((not (exercise-done current)) + (format t "~&~a~%" + (yellow "This exercise hasn't passed its checks yet. h for a hint, r to rerun."))) + (t + (let ((next (or (next-pending-index index) + (next-pending-index -1)))) + (cond (next + (setf index next) + (set-current-name (exercise-name (nth index *exercises*))) + (run-and-show (nth index *exercises*))) + (t + (clear-screen) + (format t "~&~a~%~%" (green "All exercises done!")) + (format t "~a~%~%" (info-field :final)) + (format t "r rerun · l list · q quit~%~%")))))))) + ((string-equal cmd "h") + (show-hint (nth index *exercises*))) + ((or (string-equal cmd "r") (string= cmd "")) + (run-and-show (nth index *exercises*))) + ((string-equal cmd "l") + (list-exercises :all)) + ((string-equal cmd "q") + (return-from watch-loop)) + (t + (format t "~&Unknown command: ~a~%" cmd) + (format t "~&n next · h hint · r rerun · l list · q quit~%~%")))) + (let ((was (exercise-mtime (nth index *exercises*)))) + (sleep 0.2) + (let ((now (exercise-mtime (nth index *exercises*)))) + (unless (eql now was) + (run-and-show (nth index *exercises*))))))) + (save-state) + (format t "~&Bye! Progress saved.~%")))) + +;;; --------------------------------------------------------------------- +;;; One-shot commands + +(defun resolve-exercise (name) + (cond (name (find-exercise name)) + (t (nth (initial-index) *exercises*)))) + +(defun run-command (name) + (let ((ex (resolve-exercise name))) + (set-current-name (exercise-name ex)) + (ensure-orig-snapshot) + (multiple-value-bind (output code timed-out-p) + (run-exercise-file (exercise-path ex)) + (format t "~a~%" output) + (cond (timed-out-p + (format t "~&~a~%" (red "Timed out.")) + (sb-ext:exit :code 1)) + ((zerop code) + (mark-done ex) + (format t "~&~a~%" (green (format nil "~a passed!" (exercise-name ex)))) + (sb-ext:exit :code 0)) + (t + (format t "~&~a~%" (red (format nil "~a failed." (exercise-name ex)))) + (sb-ext:exit :code 1)))))) + +(defun hint-command (name) + (show-hint (resolve-exercise name)) + (sb-ext:exit :code 0)) + +(defun list-command (arg) + (let ((filter (cond ((null arg) :all) + ((string-equal arg "pending") :pending) + ((string-equal arg "done") :done) + ((string-equal arg "all") :all) + (t (error "Unknown filter ~s. Use all, pending or done." arg))))) + (list-exercises filter) + (sb-ext:exit :code 0))) + +(defun reset-command (name) + (let ((ex (resolve-exercise name))) + (ensure-orig-snapshot) + (copy-file (orig-path ex) (exercise-path ex)) + (unmark-done ex) + (format t "~&The exercise ~a has been reset.~%" (exercise-name ex)) + (format t "~&(It now matches the pristine copy from when lisplings first ran here.)~%") + (sb-ext:exit :code 0))) + +(defun check-all-command () + (ensure-orig-snapshot) + (let ((passing '())) + (dolist (ex *exercises*) + (format t "~&Checking ~a/~a ... " (exercise-dir ex) (exercise-name ex)) + (finish-output) + (multiple-value-bind (output code timed-out-p) + (run-exercise-file (exercise-path ex) :timeout 30) + (declare (ignore output)) + (let ((ok (and (not timed-out-p) (zerop code)))) + (when ok (push (exercise-name ex) passing)) + (setf (exercise-done ex) ok) + (format t "~a~%" (if ok (green "ok") (red "FAILED")))))) + (setf (getf *state* :done) passing) + (let ((first-pending (find-if (complement #'exercise-done) *exercises*))) + (save-state) + (format t "~&~%Progress: ~a~%~%" (progress-bar)) + (cond (first-pending + (format t "First pending exercise: ~a~%" + (namestring (exercise-path first-pending))) + (sb-ext:exit :code 1)) + (t + (format t "All exercises pass!~%~%") + (format t "~a~%" (info-field :final)) + (sb-ext:exit :code 0)))))) + +(defun init-command (dir) + (let* ((target (pathname (if (char= #\/ (char dir (1- (length dir)))) + dir + (concatenate 'string dir "/")))) + (info (with-open-file (in (merge-pathnames "info.sexp" *source-root*)) + (read in))) + (specs (second (assoc :exercises info)))) + (ensure-directories-exist target) + (copy-file (merge-pathnames "info.sexp" *source-root*) + (merge-pathnames "info.sexp" target)) + (dolist (spec specs) + (let ((name (getf spec :name)) + (chapter (getf spec :dir))) + (dolist (kind '("exercises" "solutions")) + (copy-file (merge-pathnames (format nil "~a/~a/~a.lisp" kind chapter name) + *source-root*) + (merge-pathnames (format nil "~a/~a/~a.lisp" kind chapter name) + target))) + (let ((readme (merge-pathnames (format nil "exercises/~a/README.md" chapter) + *source-root*))) + (when (probe-file readme) + (copy-file readme + (merge-pathnames (format nil "exercises/~a/README.md" chapter) + target)))))) + (format t "~&Created a lisplings project in ~a~%~%" dir) + (format t "Next steps:~% cd ~a~% lisplings~%" dir) + (sb-ext:exit :code 0))) + +;;; --------------------------------------------------------------------- +;;; Entry point + +(defun usage () + (format t "Lisplings: small exercises to get you used to reading and~%") + (format t "writing Common Lisp code.~%~%") + (format t "Usage: lisplings [command]~%~%") + (format t "Running lisplings with no command starts the watcher: it runs~%") + (format t "the current exercise and reruns it whenever you save the file.~%~%") + (format t "Commands:~%") + (format t " run [name] run one exercise and print its output~%") + (format t " hint [name] print the hint for an exercise~%") + (format t " list [pending|done|all] list exercises with their status~%") + (format t " reset restore an exercise to its pristine state~%") + (format t " check-all run every exercise and resync progress~%") + (format t " init [dir] create a lisplings project in dir (default: ./lisplings)~%") + (format t " help show this message~%")) + +(defun main (argv) + (handler-case + (let ((command (first argv))) + (cond + ((null command) (setup) (watch) (sb-ext:exit :code 0)) + ((string-equal command "init") + (init-command (or (second argv) "lisplings"))) + ((string-equal command "help") (usage) (sb-ext:exit :code 0)) + (t + (setup) + (cond + ((string-equal command "run") (run-command (second argv))) + ((string-equal command "hint") (hint-command (second argv))) + ((string-equal command "list") (list-command (second argv))) + ((string-equal command "reset") (reset-command (second argv))) + ((string-equal command "check-all") (check-all-command)) + (t + (format t "~&Unknown command: ~a~%~%" command) + (usage) + (sb-ext:exit :code 1)))))) + (error (e) + (format *error-output* "~&lisplings: ~a~%" e) + (sb-ext:exit :code 1)))) diff --git a/src/exercise-runner.lisp b/src/exercise-runner.lisp new file mode 100644 index 0000000..6dadab1 --- /dev/null +++ b/src/exercise-runner.lisp @@ -0,0 +1,46 @@ +;;;; One Lisplings exercise, in a fresh SBCL. +;;;; +;;;; The watcher spawns this as +;;;; +;;;; sbcl --noinform --no-sysinit --no-userinit --disable-debugger \ +;;;; --script src/exercise-runner.lisp EXERCISE-PATH +;;;; +;;;; It loads the check harness, loads the exercise, then runs the +;;;; recorded checks. Exit codes: +;;;; 0 every check passed +;;;; 1 some checks failed +;;;; 2 the exercise did not load +;;;; 3 the check harness itself failed + +(in-package #:common-lisp-user) + +(defun argv-tail () + ;; Under --script, *posix-argv* is ("sbcl" extra-args...). + (rest sb-ext:*posix-argv*)) + +(defun sibling-pathname (name) + (make-pathname :name name :type "lisp" :defaults *load-truename*)) + +(let ((args (argv-tail))) + (cond ((null args) + (format *error-output* + "~&usage: sbcl --script exercise-runner.lisp EXERCISE-PATH~%") + (finish-output *error-output*) + (sb-ext:exit :code 2)) + (t + (let ((exercise (first args))) + (handler-case + (progn + (load (sibling-pathname "harness")) + (load exercise)) + (error (e) + (format *error-output* "~&~%The exercise did not load:~%") + (format *error-output* " ~a~%" e) + (finish-output *error-output*) + (sb-ext:exit :code 2))) + (handler-case + (lisplings/run-checks) + (error (e) + (format *error-output* "~&~%The check harness failed: ~a~%" e) + (finish-output *error-output*) + (sb-ext:exit :code 3))))))) diff --git a/src/harness.lisp b/src/harness.lisp new file mode 100644 index 0000000..6d0cdbb --- /dev/null +++ b/src/harness.lisp @@ -0,0 +1,101 @@ +;;;; Lisplings check harness. +;;;; +;;;; The exercise runner loads this file into a fresh SBCL subprocess +;;;; right before it loads an exercise file. It gives every exercise +;;;; its check forms and prints the final report: +;;;; +;;;; (check FORM) FORM must evaluate to non-NIL. +;;;; (check-equal EXPECTED FORM) FORM must evaluate EQUAL to EXPECTED. +;;;; (check-error FORM [TYPE]) FORM must signal an error of TYPE. + +(in-package #:common-lisp-user) + +(defparameter *lisplings/checks* '() + "Recorded checks, most recent first.") + +(defstruct (lisplings-check (:constructor %lisplings/make-check)) + description kind expected thunk) + +(defun %lisplings/record (description kind expected thunk) + (push (%lisplings/make-check :description description :kind kind + :expected expected :thunk thunk) + *lisplings/checks*) + (values)) + +(defmacro check (&body body) + "Record a check: BODY must evaluate to a non-NIL value." + (let ((form (if (null (cdr body)) (car body) `(progn ,@body)))) + `(%lisplings/record ',form :truthy nil (lambda () ,form)))) + +(defmacro check-equal (expected form) + "Record a check: FORM must evaluate EQUAL to EXPECTED." + `(%lisplings/record ',form :equal ,expected (lambda () ,form))) + +(defmacro check-error (form &optional (condition-type ''error)) + "Record a check: FORM must signal an error of type CONDITION-TYPE." + `(%lisplings/record ',form :error ,condition-type (lambda () ,form))) + +(defun %lisplings/ok (check) + (format t "~&ok ~s~%" (lisplings-check-description check)) + t) + +(defun %lisplings/fail (check explanation) + (format t "~&FAIL ~s~% ~a~%" + (lisplings-check-description check) explanation) + nil) + +(defun %lisplings/run-one (check) + (ecase (lisplings-check-kind check) + (:truthy + (handler-case + (let ((value (funcall (lisplings-check-thunk check)))) + (if value + (%lisplings/ok check) + (%lisplings/fail check + "evaluated to NIL; expected a non-NIL result"))) + (error (e) + (%lisplings/fail check (format nil "signalled an error: ~a" e))))) + (:equal + (handler-case + (let ((value (funcall (lisplings-check-thunk check)))) + (if (equal value (lisplings-check-expected check)) + (%lisplings/ok check) + (%lisplings/fail check + (format nil "got ~s, expected ~s" + value (lisplings-check-expected check))))) + (error (e) + (%lisplings/fail check (format nil "signalled an error: ~a" e))))) + (:error + (handler-case + (progn + (funcall (lisplings-check-thunk check)) + (%lisplings/fail check + (format nil "returned normally; expected it to signal ~s" + (lisplings-check-expected check)))) + (error (e) + (if (typep e (lisplings-check-expected check)) + (%lisplings/ok check) + (%lisplings/fail check + (format nil "signalled ~s, expected a ~s" + (type-of e) + (lisplings-check-expected check))))))))) + +(defun lisplings/run-checks () + "Run every recorded check in file order, print a report, and exit. +Exit code 0 means every check passed." + (let* ((checks (reverse *lisplings/checks*)) + (results (mapcar #'%lisplings/run-one checks)) + (total (length results)) + (passed (count-if #'identity results))) + (finish-output *standard-output*) + (finish-output *error-output*) + (cond ((zerop total) + (sb-ext:exit :code 0)) + ((= passed total) + (format t "~&~%All ~d check~:p passed!~%" total) + (finish-output *standard-output*) + (sb-ext:exit :code 0)) + (t + (format t "~&~%~d of ~d check~:p failed.~%" (- total passed) total) + (finish-output *standard-output*) + (sb-ext:exit :code 1))))) diff --git a/src/main.lisp b/src/main.lisp new file mode 100644 index 0000000..d7f4553 --- /dev/null +++ b/src/main.lisp @@ -0,0 +1,8 @@ +;;;; Lisplings: small exercises to get you used to reading and writing +;;;; Common Lisp code. Entry point. +;;;; +;;;; Usage: sbcl --script src/main.lisp [command ...] + +(require :sb-posix) +(load (make-pathname :name "core" :type "lisp" :defaults *load-truename*)) +(lisplings:main (rest sb-ext:*posix-argv*))