
















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















587
he languages usually studied in computer scienceānamely, Pascal, C, Modula-2, and Adaāare considered imperative languages because the basic construct is a command. These languages are heavily influenced by the āvon Neumann architectureā of computers, which includes a store (memory) and an instruction counter used to identify the next instruction to be fetched from the store. The computation model has control structures that determine the sequencing of instructions, which use assignments to make incremental modifications to the store.
Imperative languages are characterized by the following properties:
The computing by effect intrinsic to imperative programming plays havoc with some of the mathematical properties that are essential to proving the correctness of programs. For example, is addition commutative in an im- perative program? Does āwrite(a+b)ā always produce the same value as āwrite(b+a)ā? Consider the following Pascal program:
program P (output); var b : integer; function a : integer; begin b := b+2; a := 5 end; begin b := 10 write(a+b) or write(b+a) end.
In fact, implementations of Pascal will most likely give different results for the two versions of this program, depending on the order of evaluation of
588 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
expressions. This anomaly is caused by the side effect in the expression be- ing evaluated, but programming by effect lies at the heart of imperative pro- gramming. If we depend on imperative programs, we must discard many of the basic properties of mathematics, such as associative and commuative laws of addition and multiplication and the distributive law for multiplica- tion over addition.
The functional programming paradigm provides an alternative notion of pro- gramming that avoids the problems of side effects. Functional languages are concerned with data objects and values instead of variables. Values are bound to identifiers, but once made, these bindings cannot change. The principal operation is function application. Functions are treated as first-class objects that may be stored in data structures, passed as parameters, and returned as function results. A functional language supplies primitive functions, and the programmer uses function constructors to define new functions. Pro- gram execution consists of the evaluation of an expression, and sequence control depends primarily on selection and recursion. A pure functional lan- guage has no assignment command; values are communicated by the use of parameters to functions. These restrictions enforce a discipline on the pro- grammer that avoids side effects. We say that functional languages are refer- entially transparent.
Principle of Refer ential T ranspar ency : The value of a function is deter- mined by the values of its arguments and the context in which the function application appears, and it is independent of the history of the execution. z
Since the evaluation of a function with the same argument produces the same value every time that it is invoked, an expression will produce the same value each time it is evaluated in a given context. Referential transparency guarantees the validity of the property of substituting equals for equals.
Work on Lisp (List processing) started in 1956 with an artificial intelligence group at MIT under John McCarthy. The language was implemented by McCarthy and his students in 1960 on an IBM 704, which also had the first Fortran implementation. Lisp was an early example of interactive comput- ing, which played a substantial role in its popularity. The original develop- ment of Lisp used S-expressions (S standing for symbolic language) with the intention of developing an Algol-like version (Lisp 2) with M-expressions (M for metalanguage). When a Lisp interpreter was written in Lisp with S-ex- pressions, Lisp 2 was dropped. The principal versions, which are based on Lisp 1.5, include Interlisp, Franz Lisp, MacLisp, Common Lisp, and Scheme.
590 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
a (^) b c
Cell diagram (or box notation):
We prefer using the box notation for S-expressions. Atoms are represented as themselves, and if the same atom is used twice in an S-expression, a single value can be shared since atoms have unique occurrences in S-ex- pressions.
The simplicity of Scheme (and Lisp) derives from its dependence on several basic functions for constructing pairs and selecting components of a pair. Two selector functions are used to investigate a pair:
car Applied to a nonatomic S-expression, car returns the left part. cdr Applied to a nonatomic S-expression, cdr returns the right part.
On the IBM 704, car stood for ācontents of address registerā and cdr for ācon- tents of decrement registerā. Some authors have suggested that āheadā and ātailā or āfirstā and ārestā are more suggestive names for these functions, but most Lisp programmers still use the traditional names.
The following examples that use brackets [ ] to delimit arguments do not follow correct Scheme syntax, which will be introduced shortly:
car [ ((a. b). c) ] = (a. b) cdr [ ((a. b). c) ] = c
An error results if either function is applied to an atom.
An abstract implementation of the selector functions can be explained in terms of a box diagram:
car returns the left pointer. cdr returns the right pointer.
a b
c
591
A single constructor function cons builds a pair given two S-expressions:
cons Applied to two S-expressions, cons returns a dotted pair contain- ing them.
For example:
cons[ p , q ] = (p. q) cons[ (a. b) , (a. c) ] = ((a. b). (a. c))
As an abstract implementation, we allocate a new cell and set its left and right components to point to the two arguments. Observe that the atom a is shared by the two pairs.
c
a b
(a. b)
(a. c)
cons [ (a. b) , (a. c) ]
The notion of an S-expression is too general for most computing tasks, so Scheme primarily deals with a subset of the S-expressions. A list in Scheme is an S-expression with one of two forms:
S-expressions that are lists use special notation:
(a. ( )) is represented by (a)
(b. (a. ( ))) is represented by (b a)
(c. (b. (a. ( )))) is represented by (c b a)
Cell diagrams for lists are usually drawn with a horizontal āspineā that stretches from left to right. The spine contains as many boxes as the list has elements at its top level.
LISTS IN SCHEME
593
Unary functions:
(add1 5) returns 6 (sub1 0) returns - (abs (add1 -5)) returns 4
Binary functions:
(- 6 9) returns - (quotient 17 5) returns 3 (/ 17 5) returns 3. (* 10 12) returns 120 (- (* 10 2) (+ 13 3)) returns 4 (modulo 53 5) returns 3
N-ary functions:
(+ 1 2 3 4 5) returns 15 (* 1 2 3 4 5) returns 120 (max 2 12 3 10) returns 12 (min (* 4 6) (+ 4 6) (- 4 6)) returns -
Miscellaneous functions:
(expt 2 5) returns 32 (expt 5 -2) returns 0. (sqrt 25) returns 5 (sqrt 2) returns 1.
Functions that return Boolean values are called predicates. In Scheme predi- cates return either the atom #t, which stands for true, or #f, the value for false. Scheme programmers usually follow the convention of naming a predi- cate with identifiers that end in a question mark.
(negative? -6) returns #t (= 6 2) returns #f (zero? 44) returns #f (< 0.5 0.1) returns #f (positive? -33) returns #f (>= 3 30) returns #f (number? 5) returns #t (<= -5 -3) returns #t (integer? 3.7) returns #f (odd? 5) returns #t (real? 82) returns #f (even? 37) returns #f (> 6 2) returns #t
When the Scheme interpreter encounters an atom, it evaluates the atom:
SCHEME EVALUATION
594 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
The define operation may be used to bind a value to an atom. The operation makes the binding and returns a value:
(define a 5) returns a (define b 3) returns b a returns 5 (+ a b) returns 8 (+ a c) returns an error since c has no value bound to it.
Although the value returned by define is unspecified in the Scheme standard, most Schemes return the name of the identifier that has just been bound.
When the Scheme interpreter evaluates a list, it expects the first item in the list to be an expression that represents a function. The rest of the items in the list are evaluated and given to the function as argument values.
(* a (add1 b)) returns 20
Suppose now that we want to apply car to the list (a b c). Evaluating the expression (car (a b c)) means that a must represent a function, which will be applied to the values of b and c, and the resulting value is passed to car. Since we want to apply car to the list (a b c) without evaluating the list, we need a way to suppress that evaluation. Scheme evaluation is inhibited by the quote operation.
(quote a) returns the symbol a (quote (a b c)) returns (a b c) unevaluated (car (quote (a b c))) returns a (cdr (quote (a b c))) returns (b c) (cons (quote x) (quote (y z))) returns the list (x y z)
The quote operation may be abbreviated by using an apostrophe.
(cdr '((a) (b) (c))) returns ((b) (c)) (cons 'p '(q)) returns (p q) (number? 'a) returns #f 'a returns a '(1 2 3) returns (1 2 3)
The car and cdr functions may be abbreviated to simplify expressions. (car (cdr '(a b c))) may be abbreviated as (cadr '(a b c)). Any combination of aās and dās between c and r (up to four operations) defines a Scheme selector func- tion.
596 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
equality of numeric atoms can be tested using the = function. The equality of general S-expressions will be considered later.
All the operations considered so far do not act in the same way. Scheme functions, such as +, car, null?, =, and user-defined functions, always evalu- ate their arguments. In fact, when (+ (car '(2 4 6)) 5) is submitted to the inter- preter, each of the expressions +, (car '(2 4 6)), and 5 are evaluated:
On the other hand, several of the operations described so far do not and cannot evaluate all of their operands. (quote a) simply returns its operand unevaluated. (define x (+ 5 6)) evaluates its second argument, but leaves its first argument unevaluated.
These operations are called special for ms to distinguish them from normal Scheme functions. A complete list of the special forms in Scheme follows:
and delay let quasiquote begin do let* quote case if letrec set! cond lambda or while define
For some of these special forms, the determination of which arguments are evaluated is made on a dynamic basis using the results of evaluations per- formed so far. We will not take the time to describe all of the special forms in Scheme. The description of those not used in this appendix can be found in the references for Scheme.
The special form define returns the name of the function (or other object) being defined; more importantly, it has the side effect of binding an object that may be a function to the name.
(define name (lambda (list-of-parameters) expression))
The use of lambda here will be explained later. The basic idea is that execut- ing the function defined by the expression (lambda (list-of-parameters) ex- pression) involves evaluating the expression in an environment that contains
597
binding of the parameters in the list to actual arguments. We give examples to illustrate user-defined Scheme functions below.
(define hypotenuse (lambda (a b) (sqrt (+ (* a a) (* b b))) )) (hypotenuse 3 4) returns 5. (hypotenuse 10 20) returns 22.
(define first (lambda (L) (car L))) (first '((a b c))) returns (a b c)
(define second (lambda (L) (cadr L) )) (second '((a) (b) (c))) returns (b)
What if the value bound to L does not have a first or second element? We use revisions to these two functions to illustrate conditional expressions in Scheme. We plan to change the definition so that
If L is empty, both functions return #f. If L has only one element, second returns #f.
A mechanism for making decisions is needed to carry out these revisions. Decisions in Scheme are represented as conditional expressions using the special form cond:
(cond (c 1 e 1 ) (c 2 e 2 ) ⦠(cn en) (else en+1) ),
which is equivalent to if c 1 then return e (^1)
else if c 2 then return e (^2) : else if c (^) n then return en else return en+
If all of c 1 , c 2 , ā¦, c (^) n are false and the else clause is omitted, the cond result is unspecified, although many implementations return an empty list. The func- tion cond is a special form since it does not evaluate all its arguments. For the purposes of testing, any non-#f value represents true.
Now we use cond to revise the definitions of the functions first and second.
(define first (lambda (L) (cond ((null? L) #f) (else (cdr L)) )))
DEFINING FUNCTIONS IN SCHEME
599
= 2 ⢠[2 ⢠[2 ⢠(power 2 0)]] = 2 ⢠[2 ⢠[2 ⢠1]] = 2 ⢠[2 ⢠2] = 2 ⢠4 = 8
fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) for n> (define fib (lambda (n) (cond ((zero? n) 1) ((zero? (sub1 n)) 1) (else (+ (fib (sub1 n)) (fib (- n 2)) )) )))
Scheme contains a mechanism for defining anonymous functions, as was the case in the lambda calculus (see Chapter 5). The lambda expression λx,y. y^2 +x becomes the S-expression (lambda (x y) (+ (* y y) x)) in Scheme. An anony- mous function can appear anywhere that a function identifier is allowed. For example, we can apply the previous function as follows:
((lambda (x y) (+ (* y y) x)) 3 4) returns 19.
In fact, the expression that we use to define a function is simply making a binding of an identifier to a lambda expression representing an anonymous function. For example, the expression (define fun (lambda (x y) (+ (* y y) x))) binds the name fun to the anonymous function (lambda (x y) (+ (* y y) x))). Scheme permits an abbreviation of such a definition using notation that shows the pattern of a call of the function as in
(define (fun x y) (+ (* y y) x)).
Many functions in Scheme manipulate lists. Therefore we develop three ex- amples that show the basic techniques of processing a list recursively.
Case 1 : List is empty ā return 0 Case 2 : List is not empty ā it has a first element that is an atom ā return (1 + number of atoms in the cdr of the list).
RECURSIVE DEFINTIONS
600 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
In Scheme, cond can be used to select one of the two cases. (define count1 (lambda (L) (cond ((null? L) 0) (else (add1 (count1 (cdr L)))) )))
Case 1 : List is empty ā return 0
Case 2 : List is not empty. Subcase a : First element is an atom (it not is a pair) ā return (1 + number of atoms in the cdr of the list). Subcase b : First element is not an atom ā return the number of atoms in the cdr of the list.
We write this algorithm in Scheme as the function (define count2 (lambda (L) (cond ((null? L) 0) ((atom? (car L)) (add1 (count2 (cdr L)))) (else (count2 (cdr L))) )))
Case 1 : List is empty ā return 0
Case 2 : List is not empty. Subcase a : First element is an atom ā return (1 + number of atoms in the cdr of the list). Subcase b : First element is not an atom ā return (the number of atoms in the car of the list
The corresponding Scheme function is defined below. (define count3 (lambda (L) (cond ((null? L) 0) ((atom? (car L)) (add1 (count3 (cdr L)))) (else (+ (count3 (car L)) (count3 (cdr L)) )) )))
Now that we have seen the basic patterns for defining functions that process lists, we describe a number of useful list manipulation functions, most of which are predefined in Scheme. We give them as user-defined functions as
602 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
For example, (concat '(a b c) '(d e)) becomes (cons 'a (concat '(b c) '(d e))) = (cons 'a (cons 'b (concat '(c) '(d e)))) = (cons 'a (cons 'b (cons 'c (concat '( ) '(d e))))) = (cons 'a (cons 'b (cons 'c '(d e)))) = (cons 'a (cons 'b '(c d e))) = (cons 'a '(b c d e)) = (a b c d e) Although its name may suggest otherwise, this is a pure function, so nei- ther argument is altered. If length(L1) = n, concat requires n applications of cons; this is a measure of how much work is done. The predefined function for concatenating lists is called append and allows an arbitrary number of lists as its arguments. User functions with an arbitrary number of argu- ments can be defined several ways, but that topic is beyond the scope of this presentation.
(define reverse (lambda (L) (if (null? L) '( ) (concat (reverse (cdr L)) (list (car L))) ))) The diagram below shows the way reverse handles a list with four ele- ments. Observe that we assume that the function works correctly on lists of length three (the induction hypothesis).
(a b c d)
a (b^ c^ d)
car cdr
(d c b) (a)
list^ reverse
concat (d c b a)
(define member (lambda (e L) (cond ((null? L) #f) ((equal? e (car L)) L) (else (member e (cdr L))) )))
603
We might expect this Boolean function to return #t (true) or #f (false), but it returns the rest of the list starting with the matched element for true. This behavior is consistent with the interpretation that any non-#f object repre- sents true. If the item is not in the list (the first case in the cond expres- sion), member returns #f.
(define and (lambda (s1 s2) (if s1 s2 #f) )) (define or (lambda (s1 s2) (if s1 s2 #t) )) The predefined āandā and āorā operations (actually special forms) allow an arbitrary number of S-expressions as arguments. In these functions and in our user-defined functions, the arguments are tested from left to right until a decision can be made. For and, the first false argument makes the result #f. For or, the first true argument makes the result non-#f.
Since we defined and and or as regular functions, all of the arguments in a call must be evaluated even if they are not all needed. The special forms and and or evaluate only as many operands as are needed to make a deci- sion.
In Lisp 1.5 and many of its successors, access to nonlocal identifiers is re- solved by dynamic scoping: the calling chain (along dynamic links) is fol- lowed until the identifier is found local to a program unit (a function in Lisp). McCarthy claims that he intended for Lisp to have static scoping but that a mistake was made in implementing the early versions of Lisp(see [Wexelblat81]). In fact, dynamic scoping is easier to implement for Lisp.
Scheme and Common Lisp use static scoping; nonlocal references in a func- tion are resolved at the point of function definition. Static scoping is imple- mented by associating a closure (instruction pointer and environment pointer) with each function as it is defined. The calling stack maintains static links for nonlocal references.
Top-level defineās create a global environment composed of the identifiers being defined that is visible everywhere. A new scope is created in Scheme when the formal parameters, which are local identifiers, are bound to actual values when a function is invoked. The following transcript shows the cre- ation of a global identifier a and a local (to f) identifier a.
(define a 22) a a 22
SCOPE RULES IN SCHEME
605
(letrec ((fact (lambda (n) (cond ((zero? n) 1) (else (* n (fact (sub1 n)))))))) (fact 5)) 120
See Chapter 10 for an explanation of the meaning of letrec in terms of fixed points.
Reasoning about the correctness of programs in imperative languages can be a formidable challenge (see Chapter 11).
Functional languages are much easier to reason about because of referential transparency: Only those values immediately involved in a function applica- tion need to be considered. Programs defined as recursive functions usually can be proved correct by an induction proof. Consider a Scheme function that computes the sum of the squares of a list of integers.
(define sumsqrs (lambda (L) (cond ((null? L) 0) (else (+ (* (car L) (car L)) (sumsqrs (cdr L)))))
Notation: If L is a list, let L (^) k denote the kth^ element of L.
Precondition : L is a list of zero or more integers.
Proof of correctness: By induction on the length n of L.
Basis : n = length(L) = 0
Induction step : Suppose that for any list M of length n,
Let L be a list of length n+1. Note that (cdr L) is a list of length n.
Therefore (sumsqrs L) = L 12 + (sumsqrs (cdr L))
PROVING CORRECTNESS IN SCHEME
606 APPENDIX B FUNCTIONAL PROGRAMMING WITH SCHEME
Much of the expressiveness of functional programming comes from treating functions as first-class objects with the same rights as other objectsānamely, to be stored in data structures, to be passed as parameters to subprograms, and to be returned as function results.
In Scheme, functions can be bound to identifiers using define and may also be stored in structures:
(define fn-list (list add1 ā (lambda (n) (* n n))))
or alternatively
(define fn-list (cons add (cons ā (cons (lambda (n) (* n n)) '( )))))
defines a list of three unary functions.
fn-list returns (#
A Scheme procedure can be defined to apply each of these functions to a number: (define construction (lambda (fl x) (cond ((null? fl) '( )) (else (cons ((car fl) x) (construction (cdr fl) x)))))) so that
(construction fn-list 5) returns (6 ā5 25).
The function construction is based on an operation found in FP, a functional language developed by John Backus (see [Backus78]). It illustrates the pos- sibility of passing functions as arguments.
Since functions are first-class objects in Scheme, they may be stored in any sort of structure. It is possible to imagine an application for a stack of func- tions or even a tree of functions.
Definition : A function is called higher -order if it has one or more functions as parameters or returns a function as its result. z
Higher-order functions are sometimes called functional forms since they al- low the construction of new functions from already defined functions. The expressiveness of functional programming comes from the use of functional forms that allow the development of complex functions from simple func- tions using abstract patternsāfor example, construction defined above. We continue, describing several of the most useful higher-order functions.