Concepts of Programming Languages

(Sean Pound) #1

282 Chapter 6 Data Types


In this list, (B C) is a list nested inside the outer list.
Data and code have the same syntactic form in LISP and its descendants.
If the list (A B C) is interpreted as code, it is a call to the function A with
parameters B and C.
The fundamental list operations in Scheme are two functions that take lists
apart and two that build lists. The CAR function returns the first element of its
list parameter. For example, consider the following example:

(CAR '(A B C))

The quote before the parameter list is to prevent the interpreter from consider-
ing the list a call to the A function with the parameters B and C, in which case
it would interpret it. This call to CAR returns A.
The CDR function returns its parameter list minus its first element. For
example, consider the following example:

(CDR '(A B C))

This function call returns the list (B C).
Common LISP also has the functions FIRST (same as CAR), SECOND,... ,
TENTH, which return the element of their list parameters that is specified by
their names.
In Scheme and Common LISP, new lists are constructed with the CONS and
LIST functions. The function CONS takes two parameters and returns a new
list with its first parameter as the first element and its second parameter as the
remainder of that list. For example, consider the following:

(CONS 'A '(B C))

This call returns the new list (A B C).
The LIST function takes any number of parameters and returns a new list
with the parameters as its elements. For example, consider the following call
to LIST:

(LIST 'A 'B '(C D))

This call returns the new list (A B (C D)).
ML has lists and list operations, although their appearance is not like those
of Scheme. Lists are specified in square brackets, with the elements separated
by commas, as in the following list of integers:

[5, 7, 9]

[] is the empty list, which could also be specified with nil.
The Scheme CONS function is implemented as a binary infix operator in
ML, represented as ::. For example,

3 :: [5, 7, 9]
Free download pdf