Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Practice: Common Lisp Macro, CLOS and Condition Exercises

Practice Common Lisp with graded exercises on macros, CLOS, conditions and tooling, with worked solutions, idioms, common pitfalls and a style checklist.

You learn Lisp by writing it. Below are exercises for each chapter of this part of the course, with solutions to compare against after you have tried. Write each one in a REPL (SBCL is a good choice) and check macros with macroexpand-1.

No Common Lisp implementation runs on this site, so the Lisp exercises and solutions are read-only; run them locally. The JavaScript TryIts are labelled stand-ins: a small macro-expansion workbench and a checker for exercise logic.

How to practice

  1. Try the exercise for at least ten minutes before reading the solution.
  2. Run your code, then run the edge cases: empty input, one element, nil, wrong types.
  3. For macros, always read the expansion. For CLOS, call with an unexpected class to see no-applicable-method.
  4. Rewrite your solution in a second way, for example with loop and then with reduce.

Macro exercises

M1. Write (while test body...). M2. Write (swap a b) safely. M3. Write (when-let (var expr) body...) that binds var to expr and runs the body only when the value is not nil. M4. Write (repeat n body...) that evaluates n once and uses no visible variable. M5. Write (with-timing (label) body...) that prints elapsed time and returns the body's values. M6. Write (defconst-list name items...) that defines a constant list.

Solutions for M1, M2, M4 and M5:

LISP
(defmacro while (test &body body)
  `(loop (unless ,test (return)) ,@body))

(defmacro swap (a b)
  (let ((tmp (gensym "TMP")))
    `(let ((,tmp ,a)) (setf ,a ,b ,b ,tmp))))

(defmacro repeat (n &body body)
  (let ((i (gensym "I")) (limit (gensym "LIMIT")))
    `(let ((,limit ,n))
       (do ((,i 0 (1+ ,i))) ((>= ,i ,limit))
         ,@body))))

(defmacro with-timing ((label) &body body)
  (let ((start (gensym "START")))
    `(let ((,start (get-internal-real-time)))
       (multiple-value-prog1 (progn ,@body)
         (format t "~a took ~d ticks~%" ,label (- (get-internal-real-time) ,start))))))

Notice multiple-value-prog1, which preserves all return values of the body, and the single evaluation of n. These are exactly the traps from variable capture and multiple evaluation.

JS Stand-in: a macro workbench (edit and expand)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

CLOS exercises

C1. Define shape, circle, rectangle and a generic area. C2. Add a generic describe-shape using call-next-method so subclasses extend the base text. C3. Add a logged-mixin with an :before method on area that prints the call. C4. Make print-object show #<CIRCLE r=2>. C5. Use an eql specializer to implement (command :quit), (command :help). C6. Define a multiple-dispatch generic intersect for two shapes.

Solution sketch for C2 and C3:

LISP
(defgeneric describe-shape (s))
(defmethod describe-shape ((s shape)) "a shape")
(defmethod describe-shape ((s circle))
  (format nil "~a, specifically a circle of radius ~a" (call-next-method) (radius s)))

(defclass logged-mixin () ())
(defmethod area :before ((x logged-mixin))
  (format t "[log] computing area of ~a~%" (type-of x)))
(defclass logged-circle (logged-mixin circle) ())

For C6 try three shapes first (circle, rectangle, triangle): the nine combinations show why symmetric cases should call each other, as in the collision example of the generic functions lesson.

Condition exercises

E1. Define parse-error-in-line with slots line and text and a :report. E2. Write parse-number-list that parses a list of strings and offers the restarts skip-item and use-default. E3. Write a caller that collects all bad items with handler-bind and still returns the good ones. E4. Write with-temp-file using unwind-protect that deletes its file even after errors. E5. Replace a case with ecase and watch the error.

Solution sketch for E2 and E3:

LISP
(defun parse-item (text)
  (restart-case
      (or (parse-integer text :junk-allowed t)
          (error 'parse-error-in-line :text text))
    (skip-item () :report "Skip this item." nil)
    (use-default (&optional (v 0)) :report "Use a default number." v)))

(defun collect-numbers (items)
  (let ((bad '()))
    (handler-bind ((parse-error-in-line
                     (lambda (c)
                       (push (text c) bad)
                       (invoke-restart 'skip-item))))
      (values (remove nil (mapcar #'parse-item items))
              (reverse bad)))))

(collect-numbers '("1" "x" "3"))   ; => (1 3), ("x")

(The second return value is built after the first form finishes, because values evaluates its arguments left to right.)

JS Stand-in: check the logic of E2/E3

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Tooling exercises

T1. Create a project with myapp.asd, package.lisp and main.lisp, and load it with ql:quickload. T2. Add a myapp/tests secondary system with three FiveAM tests and asdf:test-system. T3. Use trace to see the call tree of a recursive function. T4. Build an executable with save-lisp-and-die that takes a command-line argument. T5. Add cl-ppcre as a dependency and use :local-nicknames to import it.

Idioms to adopt

  • Use &body for macro bodies and ,@ to splice; use gensym for every temporary.
  • Use ecase, etypecase and check-type for impossible cases and API boundaries.
  • Prefer accessors to slot-value, and generic functions to typecase chains.
  • Signal conditions with data (slots), not formatted strings.
  • Put recovery options in restart-case and policy in handler-bind.
  • Write a function first; reach for defmacro only when evaluation control is needed.
  • Keep one package per subsystem, and never :use a large third-party package.

Common pitfalls

Pitfall Fix
macro argument evaluated twice bind it once with a gensym
,body instead of ,@body splice with ,@
setf on a quoted constant list build the list with list or copy-list
error caught with bare error hides bugs handle the narrowest condition
handler-case used where a restart is needed use handler-bind and invoke-restart
macro defined after its first use in the same file define macros before code that uses them
redefining a macro and expecting old callers to change recompile callers
case with strings use cond with string= or equal hash tables (case uses eql)

A short self-review

Take one of your solutions and ask: Does any macro argument appear twice? Do all macro temporaries use gensym? Does each error have a condition class? Does a generic function have an unneeded typecase? Does every system declare its dependencies? When the answers are all comfortable, you have the working habits of a Lisp programmer. Return to the course overview to continue with any chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which form preserves all return values of the body in a timing macro?

    prog1 keeps only the first value, whereas multiple-value-prog1 keeps them all.
  2. 2. In collect-numbers, which tool lets the handler pick skip-item without unwinding first?

    handler-bind runs on the signaling stack, where the restarts defined by restart-case still exist.
  3. 3. Why does case fail with string keys?

    Use cond with string=, or alexandria:switch, for strings.
  4. 4. What is the safest fix for a macro that pastes an argument twice?

    A gensym variable avoids both double evaluation and name capture.

Summary

  • Practice each chapter with small exercises, then compare with the sketches and rewrite a second way.
  • Macros: gensym every temporary, evaluate arguments once, check the expansion.
  • CLOS: use auxiliary methods and dispatch instead of conditionals; test with unexpected classes.
  • Conditions: define classes with data, offer restarts at the failure point, decide policy at the call site.
  • The JavaScript snippets are stand-ins to explore the logic; run the Lisp locally to confirm.

Next: Back to the Common Lisp course