Why do you have cons with a null value to get the correct list in the schema?

I understand this is a complete n00b question, but I'm curious, and I thought I could better explain here than anywhere else. Here is the list (I am using Dr. Scheme)

> (list 1 2 3)
(1 2 3)

What I consider to be just sugar for this:

> (cons 1 (cons 2 (cons 3 null)))
(1 2 3)

This, on the other hand, does something else:

> (cons 1 (cons 2 3))
(1 2 . 3)

My questions are: why is this so? What is the point of requiring zero at the end of the list?

+5
source share
4 answers

List definition is recursive.

 1. The null list (empty list) is a list
 2. A list is made up of an item cons a list

So these are the lists:

1. null  => ()  --read as empty list
2. cons 3 null  =>  (3)
3. cons2 (cons 3 null)  => (2, 3) 

The last example you gave cons 2 3 does not match the definition of this list, so it is not a list. This cons takes an item and a list. 3 is not a list.

+11
source

cons , , :

(cons 1 (cons 2 (cons 3 null)))

, null, (). (cons 2 3), , , 2 .

+2

Lisps, Scheme, , lisp , , .

, " ?" .

cons cons nil . cons nil, , , , .

, -, , cons . - , cons - .

, , . , , . - ; common lisp .

, : " , cons?", " , ?"

+2

The cons statement is used to highlight a pair whose car is obj1 and whose cdr is obj2

(cons obj1 obj2)

Therefore, it is necessary to end the cons statement with a zero value so that we know that we are the end of the list.

> (cons 1 (cons 2 3))
(1 2 . 3)

In this example, cdr will be a pair <2,3>, where 2 is a car and 3 is cdr. Not the same as:

(list 1 2 3)
0
source

All Articles