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?
Remember that
conssimply sticks together two things, for historical reasons the first one is referred to ascarand the second one ascdr.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 ofconsing one element ... and so on, until we reach the empty list'(). For example:When dealing with lists, think of
caras the first element of the list andcdras the rest of the elements, andconsadds 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 useappendfor that). Take a look: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: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:Finally, if we call
caron the above list, we get its first element - which happens to be'(d e f), and clearly it has 3 elements: