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

前端 未结 6 1332
北海茫月
北海茫月 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条回答
  •  情深已故
    2021-01-05 17:39

    cons uses the first argument as head of the list, and the second as tail.

    You give it a first list (1 2 3), which will constitute the head of the resulting list and a second list (4 5 6), to be used as tail of the list. Thus, you end with ((1 2 3) 4 5 6).

    Thing of lists as left-to-right combs, ending with empty list (represented as o here), and see how they combine.

     X=      Y=
     /\      /\
    1 /\  + 4 /\    
     2 /\    5 /\  
      3  o    6  o
    

    You then build:

     /\
    X  Y
    

    Obtaining:

      /\
     /\ \
    1 /\ \
     2 /\ \
      3  o/\
         4 /\
          5 /\
           6  o
    

    which is ((1 2 3) 4 5 6 when represented with parenthesis. And this is a pair of lists.

提交回复
热议问题