0
votes

In Scheme, using list to define a list ensures that the result is a proper list, meaning that its final element is a list ().

If one defines a test list:

(define test (list 27 3))

And takes the length of the list, Racket says that it is 2. When one prints the list, it only displays (27 3), not showing the ().

However, if one takes the (rest (rest test)), the () appears. Performing a (list-ref test 2) yields an error.

If the () appears as the 3rd element in the list when cdring through the elements, why isn't it considered a member of the list?

Wouldn't this create confusion between proper and improper lists in Scheme?

1

1 Answers

2
votes

A list is a chain of pairs. The elements are the cars of each pair, and each pair's cdr is a reference to the next pair in the chain.

The cdr of the last pair of a proper list is a reference to the special () object, which represents an empty list. It's not an element of the list because it's in the cdr, not the car.

The rest function returns the cdr of a pair. So (rest (rest test)) is returning the second cdr, which is () because it's at the end of the list.

There's no confusion with improper lists. An improper list has something other than () as the cdr of the last pair in the chain.