Search code examples
lispschemesicp

Scheme if pair end with a space char,the result will have one dot between two element


if pair end with a space char, why result value contains one dot(.)? what does this dot(.) mean?

(cons 1 2 )
;Value 2: (1 . 2)

(car (cons 1 2 ))
;Value: 1

(cdr (cons 1 2 ))
;Value: 2

this one seems stupid, because pair only contain two element.

i just want to know why the first expression echo one dot in the result!

(cadr (cons 1 2 ))
;The object 2, passed as an argument to safe-car, is not a pair.
;To continue, call RESTART with an option number:
; (RESTART 1) => Return to read-eval-print level 1.

thanks!


Solution

  • CONS constructs a pair. A pair of two things. It is written as (firstthing . secondthing).

    If the second thing is an empty list, it is written as (firstthing). It is the same as (firstthing . ()).

    Since cons constructs a cons, the result of (cons 1 2) is (1 . 2).

    (cadr (cons 1 2)) is an error. It is (car (cdr (cons 1 2)). (cdr (cons 1 2) is 2. Now (car 2) is wrong. You can't take the car of 2. 2 is a number, not a cons.

    If you want to create a list, which is made of cons cells or the empty list, then use the function list.