1
votes

After more or less understanding the answers to this question, it looks to me that in Racket/Scheme, at the reader level, the second element of each pair in the syntax tree has to be a list. In other words, whenever a dotted s-expression of the form (A . B) represents a vertex of the syntax tree, B can only by an s-expression that parses as a list, like (C D E). For example: (A . (C D E)). This of course can be written as (A C D E), because it is parsed identically.

(+ . (1 2 3)) ; => 6
(+ 1 2 3) ; => 6

(define . (x 1))
x ; => 1
(define y 2)
y ; => 2

My question is: what is the reason that "dotted pair" s-expressions are allowed in the Racket/Scheme syntax, other than inside literal data? Is there an example of a Racket/Scheme expression that can be written using pairs, but cannot be written simpler using lists?

1

1 Answers

3
votes

In any Lisp system, reading and evaluating are separate steps. To the reader, everything is literal data; it's the evaluator that decides what to evaluate and what (by virtue of quote and quasiquote) to treat as literal data.

The reader reads the following expressions exactly the same way:

(+ 1 2 3)
(+ . (1 2 3))
(+ . (1 . (2 3)))
(+ . (1 . (2 . (3))))
(+ . (1 . (2 . (3 . ()))))

This is because, at the basic level, non-empty lists are made up of a bunch of cons cells, which happen to have a cdr that points to another list (empty or not).

Furthermore, there are legitimate Scheme expressions that do use improper lists. Rest arguments for lambdas are a prime example of this:

(define (list . items)
  items)