In SICP exercise 2.26 using DrScheme, why does cons return a list, instead of a pair of lists?

前端 未结 6 1321
北海茫月
北海茫月 2021-01-05 17:15

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:

<         


        
6条回答
  •  萌比男神i
    2021-01-05 17:50

    '((1 2 3) 4 5 6) is actually a pair of lists. Here's another way to write it:

    '((1 2 3) . (4 5 6))
    

    However, the printer avoids dotted pair notation whenever it can, so you get the first representation instead. The rule is:

    '(x . (xs ...))
    =>
    '(x xs ...)
    

    For any x and xs. Here, your x = '(1 2 3) and xs = '(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:

    (cons (cons 1 '()) (cons 6 '()))
    

    Here, '() is nil, or the empty list. If we translate this literally to dotted-pair notation, we get this:

    '((1 . ()) . (6 . ()))
    

    But because the printer collapses dotted-pair notation whenever possible, you get this instead:

    '((1 . ()) . (6 . ()))
    =>
    '((1) . (6))    ; <-- x=1, xs=nothing; x=6, xs=nothing
    =>
    '((1) 6) ; <-- x=1, xs=6
    

提交回复
热议问题