Concepts of Programming Languages

(Sean Pound) #1

698 Chapter 15 Functional Programming Languages


given function to each element of the given list and returns a list of the results
of these applications. A Scheme definition of map follows:^9

(DEFINE (map fun a_list)
(COND
((NULL? a_list) '())
(ELSE (CONS (fun (CAR a_list))
(map fun (CDR a_list))))
))

Note the simple form of map, which expresses a complex functional form.
As an example of the use of map, suppose we want all of the elements of a
list cubed. We can accomplish this with the following:

(map (LAMBDA (num) (* num num num)) '(3 4 2 6))

This call returns (27 64 8 216).
Note that in this example, the first parameter to mapcar is a LAMBDA
expression. When EVAL evaluates the LAMBDA expression, it constructs a func-
tion that has the same form as any predefined function except that it is name-
less. In the example expression, this nameless function is immediately applied
to each element of the parameter list and the results are returned in a list.

15.5.14 Functions That Build Code


The fact that programs and data have the same structure can be exploited in
constructing programs. Recall that the Scheme interpreter uses a function named
EVAL. The Scheme system applies EVAL to every expression typed, whether it is
at the Scheme prompt in the interactive interpreter or is part of a program being
interpreted. The EVAL function can also be called directly by Scheme programs.
This provides the possibility of a Scheme program creating expressions and call-
ing EVAL to evaluate them. This is not something that is unique to Scheme, but
the simple forms of its expressions make it easy to create them during execution.
One of the simplest examples of this process involves numeric atoms. Recall
that Scheme includes a function named +, which takes any number of numeric
atoms as arguments and returns their sum. For example, (+ 3 7 10 2)
returns 22.
Our problem is the following: Suppose that in a program we have a list
of numeric atoms and need the sum. We cannot apply + directly on the list,
because + can take only atomic parameters, not a list of numeric atoms. We
could, of course, write a function that repeatedly adds the CAR of the list to the
sum of its CDR, using recursion to go through the list. Such a function follows:

(DEFINE (adder a_list)
(COND


  1. As was the case with member, map is a predefined function that cannot be redefined by users.

Free download pdf