0

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!

ray
  • 145
  • 9

2 Answers2

5

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.

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
  • 2
    @ray: A pair of two things. It is written as (firstthing . secondthing). That's the definition. That's why it is there. It could be written differently, but that's how it is defined in Lisp even before the dinosaurs walked on this planet. ;-) – Rainer Joswig Nov 15 '12 at 12:12
  • sorry,i just start learning SICP, now i finally know that the dot is just a way of representing cons.whatever, thanks a lot. – ray Nov 19 '12 at 02:31
0

The dot is not an "element" of the result, it is the way in which Scheme memorizes lists, i.e. as concatenated pairs.

For example, the list

(1 2 3)

is memorized in this form:

(1 . (2 . (3 . ())))
Svante
  • 50,694
  • 11
  • 78
  • 122
Marco L.
  • 1,489
  • 4
  • 17
  • 25
  • This is not accurate, Scheme, or any other lisp, doesn't memorize dots! It prints dots to represent conses, usually conses whose `cdr` is not null or another cons, but that may be configurable in your implementation. – acelent Nov 15 '12 at 10:13