I've started learning Scheme, for fun mostly, and because I've never used a functional language before. I chose Scheme because I wanted to read SICP for a long time.
Anyway, I'm currently learning about lists, and before that I learned about cons, car and cdr. And there's an example that creates a list of lists with cons, like this :
(cons (list 1 2) (list 3 4))
The resulting list is ((1 2) 3 4), which doesn't make sense to me, I would expect ((1 2)(3 4)) to be the result (a list made out of two lists). Why does it behave like that? I realize that if I were to use car, I would get (1 2), and cdr I'd get (3 4) becaue cdr always returns "the rest", but I don't understand why the list isn't made of two lists?
You get a list with (1 2)
as the first element (the car) and (3 4)
as the rest (the cdr) because the first argument to cons is the first element of the list and the second argument is a list containing the remaining items.
This closely resembles the structure of a list: each node of a (proper) list contains an element and a list containing all other element. cons
creates one such node.
If the second argument to cons
would become the second element of the list, how would you create a list with three arguments? You'd have to make cons
variardic at which point, it'd just be another name for list
.
If you want to create a list of lists use (list (list 1 2) (list 3 4))
.
(list (list 1 2)
(list 3 4))
is the same as
(cons (list 1 2)
(cons (list 3 4)
'()))
Which results in
((1 2) (3 4))
which can also be written as
((1 . (2 . ()))
.
((3 . (4 . ()))
.
()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With