Common Lisp Cheat Sheet
Essential Common Lisp syntax covering function and variable definitions, control flow, list operations, formatted output, and macros.
Functions & Variables
Defining functions and global/local bindings.
(defun square (x) (* x x))(defvar *count* 0) ; global, special variable(defparameter *name* "Lisp") ; global, expects reassignment(let ((x 1) (y 2)) ; local bindings (+ x y))(setf *count* (+ *count* 1))
Control Flow
Conditionals and iteration constructs.
(if (> x 0) "positive" "negative")(cond ((> x 0) "positive") ((< x 0) "negative") (t "zero"))(when (> x 0) (print "positive"))(unless (> x 0) (print "not positive"))(loop for i from 1 to 5 do (print i))
List Operations
Core functions for working with lists.
- (car lst)- returns the first element of a list
- (cdr lst)- returns the list minus its first element
- (cons a b)- constructs a new cons cell
- (list a b c)- creates a new list from arguments
- (mapcar #'fn lst)- applies fn to each element, returns a new list
- (append lst1 lst2)- concatenates lists
- (reverse lst)- returns a reversed copy of the list
- (nth n lst)- returns the nth element (zero-indexed)
Format & I/O
The format function's most common directives.
(format t "Hello, ~a!~%" "World") ; ~a = aesthetic, ~% = newline(format t "~d + ~d = ~d~%" 1 2 3) ; ~d = decimal integer(format t "~s~%" "quoted") ; ~s = write with slashify(format t "~,2f~%" 3.14159) ; ~,2f = float, 2 decimal places
Macros
Defining simple code-transforming macros.
(defmacro my-if (test then else) `(cond (,test ,then) (t ,else)))(my-if (> 5 3) (print "yes") (print "no"))(defmacro while (test &body body) `(loop while ,test do (progn ,@body)))
CLOS Classes & Generic Functions
defclass, slots, and multiple-dispatch methods.
(defclass animal () ((name :initarg :name :accessor name) (legs :initarg :legs :initform 4 :accessor legs)))(defgeneric speak (a))(defmethod speak ((a animal)) (format nil "~a makes a sound" (name a)))(defclass dog (animal) ())(defmethod speak ((d dog)) "Woof") ; specialized override(speak (make-instance 'dog :name "Rex"))
Conditions & Restarts
Signalling, handling, and recovering from errors.
(define-condition my-error (error) ((code :initarg :code :reader err-code)))(handler-case (error 'my-error :code 42) (my-error (e) (format t "caught ~a" (err-code e))))(handler-bind ((error (lambda (c) (declare (ignore c)) (invoke-restart 'continue)))) (with-simple-restart (continue "skip") (error "boom")))
Sequence Functions
Generic operations over lists and vectors.
- mapcar / mapc- map a function over one or more lists (mapc for side effects)
- reduce- fold a sequence, with :initial-value and :from-end
- remove-if / delete-if- filter out elements matching a predicate (delete is destructive)
- find / position / count- search a sequence, accept :test and :key
- sort / stable-sort- in-place sort with a comparison predicate
- subseq- extract a subsequence by start/end indices
- some / every / notany- test a predicate across sequences
Hash Tables & Structures
Key-value storage and lightweight record types.
(defvar *h* (make-hash-table :test 'equal))(setf (gethash "a" *h*) 1)(gethash "a" *h*) ; => 1 T(remhash "a" *h*)(maphash (lambda (k v) (format t "~a=~a~%" k v)) *h*)(defstruct point x y)(let ((p (make-point :x 3 :y 4))) (point-x p)) ; => 3
The LOOP Macro
Common iteration and collection idioms.
(loop for i from 1 to 5 collect (* i i)) ; => (1 4 9 16 25)(loop for x in '(1 2 3 4) when (evenp x) sum x) ; => 6(loop for (k . v) in '((a . 1) (b . 2)) do (format t "~a=~a~%" k v))(loop repeat 3 collect (random 10))(loop for i below 10 by 2 collect i) ; => (0 2 4 6 8)
Use `defparameter` (not `defvar`) when you want redefining the source file to actually update the variable's value — `defvar` only sets it if it is not already bound, which is convenient for state but confusing during iterative development.