Search code examples
listschemelispconscdr

Scheme pair construction


I am trying to understand pair construction and representation. Let's take a look at the following results:

(length (cons '(a b) '(d e f)))
=> 4

Now let's switch the order:

(length (cons '(d e f) '(a b)))
 => 3

but

(length (car (cons '(d e f) '(a b))))
=> 3

Could you please explain the results above? What is the difference between car and cdr?


Solution

  • Remember that cons simply sticks together two things, for historical reasons the first one is referred to as car and the second one as cdr.

    If the second one happens to be a proper list, then the result is also a list. Hence a list is defined as the result of consing one element with the result of consing one element ... and so on, until we reach the empty list '(). For example:

    (cons 1 (cons 2 (cons 3 '())))
    => '(1 2 3)
    

    When dealing with lists, think of car as the first element of the list and cdr as the rest of the elements, and cons adds one more element at the head of the list - that element can be anything, including another list. It just gets added at the head, the lists are not "merged" (we use append for that). Take a look:

    (car '(1 2 3))
     => 1
    
    (cdr '(1 2 3))
    => '(2 3)
    

    Now, regarding your examples - the first one adds '(a b) as the first element of a list, where the rest is '(d e f), so we now have a 4 element list, like this:

    (cons '(a b) '(d e f))
    => '((a b) d e f)
    

    Similarly for the second example: we add the first element '(d e f) to the rest of the elements '(a b), and we get a 3 element list:

    (cons '(d e f) '(a b))
    => '((d e f) a b)
    

    Finally, if we call car on the above list, we get its first element - which happens to be '(d e f), and clearly it has 3 elements:

    (car (cons '(d e f) '(a b)))
    => '(d e f)