Land of Lisp - Ch 3
TL;DR
- code and data mode
- cons cells
- making lists using
cons
,'
andlist
> (cons 1 ())
(1)
> (cons 1 (cons 2 ()))
(1 2)
> '(1 2)
(1 2)
> (list 1 2)
(1 2)
car
andcdr
Chapter 3
Code and Data Mode
> (expt 2 3) ; code mode
8
> '(expt 2 3) ; data mode
(expt 2 3)
Lists
Using cons
to create lists
> (cons 'chicken 'egg)
(CHICKEN . EGG)
> (cons 'chicken 'nil)
(CHICKEN)
> (cons 'chicken ())
(CHICKEN)
> (cons 'chicken '(egg omlette))
(CHICKEN EGG OMLETTE)
Using car
and cdr
These work up to 4 levels deep. Anything deeper (e.g. cadadar) you'll have to write yourself.
Also note that it works from back to front (look at caddr
for example)
> (car '(1 2 3 4 5))
1
> (cdr '(1 2 3 4 5))
(2 3 4 5)
> (cadr '(1 2 3 4 5))
2
> (cddr '(1 2 3 4 5))
(3 4 5)
> (caddr '(1 2 3 4 5)) ; processes in this order -> d.. d.. a
3
> (car '( (1 2) 3 4 5)) ; using a nested list
(1 2)
Creating a list, threeways... (cons
and list
)
> (cons 'chicken (cons 'egg (cons 'omlette ())))
(CHICKEN EGG OMLETTE)
> (list 'chicken 'egg 'omlette)
(CHICKEN EGG OMLETTE)
> '(chicken egg omlette)
(CHICKEN EGG OMLETTE)
> '(cat (duck bat) ant)
(CAT (DUCK BAT) ANT)