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

StackOverflow https://stackoverflow.com/questions/13393566

  •  29-11-2021
  •  | 
  •  

質問

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!

役に立ちましたか?

解決

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.

他のヒント

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 . ())))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top