The Grinnell Scheme Web: List
literals

Can you use the shorthand notation for lists when you type them in, too?

Yes, provided you remember to put a single quotation mark on the front to prevent evaluation:

> '(8 4 6 1)
(8 4 6 1)
> '()
()
These are ``list literals,'' just as '(5 . 3) is a ``pair literal.''

A hybrid notation is frequently used for ``improper lists.'' An improper list is a pair in which the second component is a pair that is not a list. (Hence improper lists are not lists.) The external representation of an improper list begins with a left parenthesis and its first components; this is followed by a space, which in turn is followed by the first component of the nested pair. If the nested pair has another pair as its second component, there is another space followed by the first component of this doubly nested pair. The process continues until a pair is reached in which the second component is not itself a pair; the components of this pair are printed with a dot between them. A right parenthesis is then appended.

> (cons 1 (cons 2 (cons 3 4)))
(1 2 3 . 4)
> (cons (cons (cons 1 2) (cons 3 4))
        (cons (cons 5 6) (cons 7 8)))
(((1 . 2) 3 . 4) (5 . 6) 7 . 8)
Programmers may prefer to avoid this hybrid notation when writing literals. For example, if one wanted to write a literal for this last construction, it would be clearer to write
'(((1 . 2) . (3 . 4)) . ((5 . 6) . (7 . 8)))
rather than
'(((1 . 2) 3 . 4) (5 . 6) 7 . 8)
although either form is permissible and results in the construction of the same data structure.


Next topic
Previous topic
Table of contents


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/scheme-web/list-literals.html


created August 8, 1995
last revised December 29, 1995

Copyright 1995 by John David Stone (stone@math.grin.edu)