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
(cons 'north 12)makes one pair, read back withcarandcdr.- Nesting three
conscalls that end innilbuilds a listequalto(list "market" "union" "civic"). (cons 'latitude 37.77)has a non-list cdr, so it prints as a dotted pair.
Keywords and builtins used here
carcdrconsdefparameterequalfirstformatlistrest
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.
Step 1 of 3 in Lists & conses, step 4 of 27 in Language basics.