typestar

Cons cells in Lisp

Every Lisp list is really a chain of two-slot cons cells.

;; a cons is one pair of slots: car on the left, cdr on the right
(defparameter *leg* (cons 'north 12))
(format t "head ~a for ~a blocks~%" (car *leg*) (cdr *leg*))

;; a list is conses chained through the cdr, with nil closing the chain
(defparameter *stops* (cons "market" (cons "union" (cons "civic" nil))))
(format t "first stop ~a, then ~a~%" (first *stops*) (rest *stops*))
(format t "hand-built but still a list: ~a~%"
        (equal *stops* (list "market" "union" "civic")))

;; a cdr that is not a list prints with a dot between the two halves
(format t "dotted pair: ~a~%" (cons 'latitude 37.77))

How it works

  1. (cons 'north 12) makes one pair, read back with car and cdr.
  2. Nesting three cons calls that end in nil builds a list equal to (list "market" "union" "civic").
  3. (cons 'latitude 37.77) has a non-list cdr, so it prints as a dotted pair.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
598
Tokens
80
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 1 of 3 in Lists & conses, step 4 of 27 in Language basics.

← Previous Next →