articles/lisp.md: add cons cells drawing

This commit is contained in:
tocariimaa 2025-02-12 15:11:38 -03:00
parent a0d6a32e14
commit 87a1bfb133

View file

@ -14,6 +14,49 @@ time. Therefore, Lisp source code directly represents the program as a tree with
A PDF of the original Lisp 1.5 manual can be found here: <https://www.lispmachine.net/books/LISP_1.5_Programmers_Manual.pdf>. Head to page 13 for
enlightenment.
## Cons cells and Lists
A list in Lisp is composed of `cons` cells which have two fields: the contained value of the cell known as `car` and a pointer to the
next cell known as `cdr`. To mark the end of a list, a special sentinel value, `NIL` is used, which represents an empty list.
```
A cons cell:
+---+---+
| O | O-|----> cdr
+---+---+
|
`'´
car
To create a cell, `cons` is used:
(cons 1 2) ; 1 and 2 are the car and cdr respectively
(car (cons 1 2)) ; ==> 1
(cdr (cons 1 2)) ; ==> 2
Also some Lisps accept the "dotted pair" notation as a shorthand:
(1 . 2)
And a list, composed of linked cons cells where `NIL` is the end sentinel:
cdr cdr cdr cdr
+---+---+ +---+---+ +---+---+ +---+---+
| O | O-|---->| O | O-|---->| O | O-|---->| o | O-|----> NIL
+-|-+---+ +---+---+ +---+---+ +---+---+
car | car | car | car |
`'´ `'´ `'´ `'´
20 "Lisp" (1 2) 39
Using cons:
(cons 20 (cons "Lisp" (cons '(1 2) (cons 39 '()))))
In cons dotted pair notation:
(20 . ("Lisp" . ('(1 2) . (39 . NIL))))
Using quote:
'(20 "Lisp" '(1 2) 39)
```
## Lisp languages in use
- [Scheme](scheme.md): created by the hackers Guy Steele and Gerald Sussman in 1975 at the MIT. Has multiple implementations, Chez Scheme,
Chicken Scheme, MIT/GNU Scheme, etc.