In SICP exercise 2.26, this Scheme code is given:
(define x (list 1 2 3))
(define y (list 4 5 6))
Then this cons call is given:
(cons x y)
I expected a pair of lists would result, ((1 2 3) (4 5 6)) but the interpreter gives,
((1 2 3) 4 5 6)
…a list with 4 elements, the first being a list. Why is y treated differently? I’ve tried looking up other SICP answers for an explanation, but couldn’t find something satisfactory. So could any Scheme/Lisp experts please shed some light on this aspect of cons? Thanks in advance for any insight.
'((1 2 3) 4 5 6)is actually a pair of lists. Here’s another way to write it:However, the printer avoids dotted pair notation whenever it can, so you get the first representation instead. The rule is:
For any
xandxs. Here, yourx = '(1 2 3)andxs = '(4 5 6), so you get((1 2 3) 4 5 6).To see how cons and dotted-pair notation is related, let’s shorten the problem to just
'(1)and'(6). The lowest level way to build a pair of them is this:Here,
'()is nil, or the empty list. If we translate this literally to dotted-pair notation, we get this:But because the printer collapses dotted-pair notation whenever possible, you get this instead: