├── LICENSE.md ├── README.md ├── TODO.txt ├── content.xml ├── html.xsl └── tests.xsl /LICENSE.md: -------------------------------------------------------------------------------- 1 | Learn Scheme is an adaptation of Structure and Interpretation of Computer Programs by Harold Abelson and Gerald Jay Sussman with Julie Sussman, second edition, published by the MIT Press. (c) 1996 by Massachusetts Institute of Technology. 2 | 3 | The content has been reformatted for the Web and made interactive by Jared Krinke. The Scheme interpreter is (c) 2015 Jared Krinke. 4 | 5 | This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. 6 | 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Learn Scheme](http://jaredkrinke.github.io/learn-scheme/) - A Complete Environment for Learning Lisp 2 | 3 | #### Do you want to learn Lisp? On your smart phone? While on the bus? Of course you do! 4 | 5 | Up until now, in order to tinker with Lisp, you'd need to download some heavyweight Lisp environment (hope your platform is supported!), configure language options, and generally spend lots of time not actually learning anything. 6 | 7 | Now, you don't have to. [Learn Scheme](http://jaredkrinke.github.io/learn-scheme/) is a complete Lisp-learning environment that fits comfortably in your browser. Thanks, Web 2.0! 8 | 9 | Additionally, through the magic (i.e. liberal licensing terms) of the [Creative Commons](http://creativecommons.org/), Learn Scheme also includes a classic textbook on programming in Lisp: *Structure and Interpretation of Computer Programs* by Abelson, Sussman, and Sussman (originally published by [MIT Press](http://mitpress.mit.edu/sicp/)). 10 | 11 | *Scheme* is a minimalist dialect of Lisp. It boils Lisp down to its clean, simple essence. *Structure and Interpretation of Computer Programs* similarly boils programming down to its essence... which it then builds up into a full-blown Lisp interpreter and compiler. That's right, you get to learn Lisp by implementing Lisp in Lisp! That's a lot of Lisp! 12 | 13 | If you're intrigued, [continue on](http://jaredkrinke.github.io/learn-scheme/) to get started with the wonderful world of Lisp! If not, go read some of [Paul Graham's essays on Lisp](http://www.paulgraham.com/lisp.html). Still not feeling motivated? Here is why you should be inspired to tackle Lisp: 14 | 15 | > "LISP is worth learning for a different reason -- the profound enlightenment experience you will have when you finally get it. That experience will make you a better programmer for the rest of your days, even if you never actually use LISP itself a lot." 16 | > -- Eric S. Raymond, How to Become a Hacker 17 | 18 | [Now go try it!](http://jaredkrinke.github.io/learn-scheme/) 19 | -------------------------------------------------------------------------------- /TODO.txt: -------------------------------------------------------------------------------- 1 | Code in tables should probably be red and not blocks (just remove the code tags)... 2 | 3 | (Ongoing...) Need to handle discontinuous programs (e.g. defining a variable in one block and using it in another) 4 | 5 | -------------------------------------------------------------------------------- /content.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 |

A Complete Environment for Learning Lisp

6 |

Do you want to learn Lisp? On your smart phone? While on the bus? Of course you do!

7 |

Get Started!

8 |
9 |

Up until now, in order to tinker with Lisp, you'd need to download some heavyweight Lisp environment (hope your platform is supported!), configure language options, and generally spend lots of time not actually learning anything.

10 |

Now, you don't have to. is a complete Lisp-learning environment that fits comfortably in your browser. Thanks, Web 2.0!

11 |

Additionally, through the magic (i.e. liberal licensing terms) of the Creative Commons, also includes a classic textbook on programming in Lisp: Structure and Interpretation of Computer Programs by Abelson, Sussman, and Sussman (originally published by MIT Press).

12 |

Scheme is a minimalist dialect of Lisp. It boils Lisp down to its clean, simple essence. Structure and Interpretation of Computer Programs similarly boils programming down to its essence... which it then builds up into a full-blown Lisp interpreter and compiler. That's right, you get to learn Lisp by implementing Lisp in Lisp! That's a lot of Lisp!

13 |

If you're intrigued, continue on to get started with the wonderful world of Lisp! If not, go read some of Paul Graham's essays on Lisp. Still not feeling motivated? Here is why you should be inspired to tackle Lisp:

14 | LISP is worth learning for a different reason -- the profound enlightenment experience you will have when you finally get it. That experience will make you a better programmer for the rest of your days, even if you never actually use LISP itself a lot. 15 |
16 | 17 | 18 |
19 | is a tiny, interactive implementation of the Scheme programming language that runs in your browser. 20 |

Scheme is a minimalist variant of Lisp that can be studied in order to understand Lisp in general. Lisp is frequently touted as a "powerful" programming language because of its unique design in which code is just data that can be manipulated or transformed in order to create new programs at run-time.

21 | 22 | 23 |

is an interactive environment for learning Scheme. At any time, you can click the Launch Editor button in the navigation bar at the top of the screen to launch the editor. Note that, on small screens, you may need to expand the navigation bar in order to find the Launch Editor button.

24 |

Once you're in the editor, you can type Scheme code into the Input text box. When you want to execute your code, simply click the Evaluate button or press Ctrl+Enter. The output of the evaluation will be displayed in the Output text box.

25 |

To navigate the content on , use the Next, Contents, and Previous links at the top and bottom of each page.

26 |
27 | 28 | 29 |

Below, you'll find a sample of Scheme code in a text box, followed by the expected output of evaluating the code.

30 |

If you'd like to try the code out, click the Try it button on the right side of the example code text box or double-click the text box itself to launch the editor with the example code. Once the editor is shown, you can follow the instructions above to evaluate the code and view the output.

31 |

As an example, the following code

32 | 33 | (+ 1 2) 34 | 35 |

evaluates to:

36 | 3 37 |
38 | 39 | 40 |

I hope you enjoy using ! If you have any suggestions or if you run into any issues, please open a new issue on the GitHub issue tracker.

41 |
42 |
43 |
44 | 45 | 46 |
47 | The acts of the mind, wherein it exerts its power over simple ideas, are chiefly these three: 1. Combining several simple ideas into one compound one, and thus all complex ideas are made. 2. The second is bringing two ideas, whether simple or complex, together, and setting them by one another so as to take a view of them at once, without uniting them into one, by which it gets all its ideas of relations. 3. The third is separating them from all other ideas that accompany them in their real existence: this is called abstraction, and thus all its general ideas are made. 48 |

We are about to study the idea of a computational process. Computational processes are abstract beings that inhabit computers. As they evolve, processes manipulate other abstract things called data. The evolution of a process is directed by a pattern of rules called a program. People create programs to direct processes. In effect, we conjure the spirits of the computer with our spells.

49 |

A computational process is indeed much like a sorcerer's idea of a spirit. It cannot be seen or touched. It is not composed of matter at all. However, it is very real. It can perform intellectual work. It can answer questions. It can affect the world by disbursing money at a bank or by controlling a robot arm in a factory. The programs we use to conjure processes are like a sorcerer's spells. They are carefully composed from symbolic expressions in arcane and esoteric programming languages that prescribe the tasks we want our processes to perform.

50 |

A computational process, in a correctly working computer, executes programs precisely and accurately. Thus, like the sorcerer's apprentice, novice programmers must learn to understand and to anticipate the consequences of their conjuring. Even small errors (usually called bugs or glitches) in programs can have complex and unanticipated consequences.

51 |

Fortunately, learning to program is considerably less dangerous than learning sorcery, because the spirits we deal with are conveniently contained in a secure way. Real-world programming, however, requires care, expertise, and wisdom. A small bug in a computer-aided design program, for example, can lead to the catastrophic collapse of an airplane or a dam or the self-destruction of an industrial robot.

52 |

Master software engineers have the ability to organize programs so that they can be reasonably sure that the resulting processes will perform the tasks intended. They can visualize the behavior of their systems in advance. They know how to structure programs so that unanticipated problems do not lead to catastrophic consequences, and when problems do arise, they can debug their programs. Well-designed computational systems, like well-designed automobiles or nuclear reactors, are designed in a modular manner, so that the parts can be constructed, replaced, and debugged separately.

53 |

We need an appropriate language for describing processes, and we will use for this purpose the programming language Lisp. Just as our everyday thoughts are usually expressed in our natural language (such as English, French, or Japanese), and descriptions of quantitative phenomena are expressed with mathematical notations, our procedural thoughts will be expressed in Lisp. Lisp was invented in the late 1950s as a formalism for reasoning about the use of certain kinds of logical expressions, called recursion equations, as a model for computation. The language was conceived by John McCarthy and is based on his paper "Recursive Functions of Symbolic Expressions and Their Computation by Machine" (McCarthy 1960).

54 |

Despite its inception as a mathematical formalism, Lisp is a practical programming language. A Lisp interpreter is a machine that carries out processes described in the Lisp language. The first Lisp interpreter was implemented by McCarthy with the help of colleagues and students in the Artificial Intelligence Group of the MIT Research Laboratory of Electronics and in the MIT Computation Center.

The Lisp 1 Programmer's Manual appeared in 1960, and the Lisp 1.5 Programmer's Manual (McCarthy 1965) was published in 1962. The early history of Lisp is described in McCarthy 1978.

55 | Lisp, whose name is an acronym for LISt Processing, was designed to provide symbol-manipulating capabilities for attacking programming problems such as the symbolic differentiation and integration of algebraic expressions. It included for this purpose new data objects known as atoms and lists, which most strikingly set it apart from all other languages of the period.

56 |

Lisp was not the product of a concerted design effort. Instead, it evolved informally in an experimental manner in response to users' needs and to pragmatic implementation considerations. Lisp's informal evolution has continued through the years, and the community of Lisp users has traditionally resisted attempts to promulgate any "official" definition of the language. This evolution, together with the flexibility and elegance of the initial conception, has enabled Lisp, which is the second oldest language in widespread use today (only Fortran is older), to continually adapt to encompass the most modern ideas about program design. Thus, Lisp is by now a family of dialects, which, while sharing most of the original features, may differ from one another in significant ways. The dialect of Lisp used in this book is called Scheme.

The two dialects in which most major Lisp programs of the 1970s were written are MacLisp (Moon 1978; Pitman 1983), developed at the MIT Project MAC, and Interlisp (Teitelman 1974), developed at Bolt Beranek and Newman Inc. and the Xerox Palo Alto Research Center. Portable Standard Lisp (Hearn 1969; Griss 1981) was a Lisp dialect designed to be easily portable between different machines. MacLisp spawned a number of subdialects, such as Franz Lisp, which was developed at the University of California at Berkeley, and Zetalisp (Moon 1981), which was based on a special-purpose processor designed at the MIT Artificial Intelligence Laboratory to run Lisp very efficiently. The Lisp dialect used in this book, called Scheme (Steele 1975), was invented in 1975 by Guy Lewis Steele Jr. and Gerald Jay Sussman of the MIT Artificial Intelligence Laboratory and later reimplemented for instructional use at MIT. Scheme became an IEEE standard in 1990 (IEEE 1990). The Common Lisp dialect (Steele 1982, Steele 1990) was developed by the Lisp community to combine features from the earlier Lisp dialects to make an industrial standard for Lisp. Common Lisp became an ANSI standard in 1994 (ANSI 1994).

57 |

58 |

Because of its experimental character and its emphasis on symbol manipulation, Lisp was at first very inefficient for numerical computations, at least in comparison with Fortran. Over the years, however, Lisp compilers have been developed that translate programs into machine code that can perform numerical computations reasonably efficiently. And for special applications, Lisp has been used with great effectiveness.

One such special application was a breakthrough computation of scientific importance -- an integration of the motion of the Solar System that extended previous results by nearly two orders of magnitude, and demonstrated that the dynamics of the Solar System is chaotic. This computation was made possible by new integration algorithms, a special-purpose compiler, and a special-purpose computer all implemented with the aid of software tools written in Lisp (Abelson et al. 1992; Sussman and Wisdom 1992).

59 | Although Lisp has not yet overcome its old reputation as hopelessly inefficient, Lisp is now used in many applications where efficiency is not the central concern. For example, Lisp has become a language of choice for operating-system shell languages and for extension languages for editors and computer-aided design systems.

60 |

If Lisp is not a mainstream language, why are we using it as the framework for our discussion of programming? Because the language possesses unique features that make it an excellent medium for studying important programming constructs and data structures and for relating them to the linguistic features that support them. The most significant of these features is the fact that Lisp descriptions of processes, called procedures, can themselves be represented and manipulated as Lisp data. The importance of this is that there are powerful program-design techniques that rely on the ability to blur the traditional distinction between "passive" data and "active" processes. As we shall discover, Lisp's flexibility in handling procedures as data makes it one of the most convenient languages in existence for exploring these techniques. The ability to represent procedures as data also makes Lisp an excellent language for writing programs that must manipulate other programs as data, such as the interpreters and compilers that support computer languages. Above and beyond these considerations, programming in Lisp is great fun.

61 |
62 | 63 |
64 |

A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize our ideas about processes. Thus, when we describe a language, we should pay particular attention to the means that the language provides for combining simple ideas to form more complex ideas. Every powerful language has three mechanisms for accomplishing this:

65 |
    66 |
  • primitive expressions, which represent the simplest entities the language is concerned with,
  • 67 |
  • means of combination, by which compound elements are built from simpler ones, and
  • 68 |
  • means of abstraction, by which compound elements can be named and manipulated as units.
  • 69 |
70 |

In programming, we deal with two kinds of elements: procedures and data. (Later we will discover that they are really not so distinct.) Informally, data is "stuff" that we want to manipulate, and procedures are descriptions of the rules for manipulating the data. Thus, any powerful programming language should be able to describe primitive data and primitive procedures and should have methods for combining and abstracting procedures and data.

71 |

In this chapter we will deal only with simple numerical data so that we can focus on the rules for building procedures.

The characterization of numbers as "simple data" is a barefaced bluff. In fact, the treatment of numbers is one of the trickiest and most confusing aspects of any programming language. Some typical issues involved are these: Some computer systems distinguish integers, such as 2, from real numbers, such as 2.71. Is the real number 2.00 different from the integer 2? Are the arithmetic operations used for integers the same as the operations used for real numbers? Does 6 divided by 2 produce 3, or 3.0? How large a number can we represent? How many decimal places of accuracy can we represent? Is the range of integers the same as the range of real numbers? Above and beyond these questions, of course, lies a collection of issues concerning roundoff and truncation errors -- the entire science of numerical analysis. Since our focus in this book is on large-scale program design rather than on numerical techniques, we are going to ignore these problems. The numerical examples in this chapter will exhibit the usual roundoff behavior that one observes when using arithmetic operations that preserve a limited number of decimal places of accuracy in noninteger operations.

72 | In later chapters we will see that these same rules allow us to build procedures to manipulate compound data as well.

73 |
74 |

One easy way to get started at programming is to examine some typical interactions with an interpreter for the Scheme dialect of Lisp. Imagine that you are sitting at a computer terminal. You type an expression, and the interpreter responds by displaying the result of its evaluating that expression.

75 |

One kind of primitive expression you might type is a number. (More precisely, the expression that you type consists of the numerals that represent the number in base 10.) If you present Lisp with a number

76 | 486 77 |

the interpreter will respond by printing

Throughout this book, when we wish to emphasize the distinction between the input typed by the user and the response printed by the interpreter, we will show the latter in a block quote.

78 |

79 | 486 80 |

Expressions representing numbers may be combined with an expression representing a primitive procedure (such as + or *) to form a compound expression that represents the application of the procedure to those numbers. For example:

81 | (+ 137 349) 82 | 486 83 | (- 1000 334) 84 | 666 85 | (* 5 99) 86 | 495 87 | (/ 10 5) 88 | 2 89 | (+ 2.7 10) 90 | 12.7 91 |

Expressions such as these, formed by delimiting a list of expressions within parentheses in order to denote procedure application, are called combinations. The leftmost element in the list is called the operator, and the other elements are called operands. The value of a combination is obtained by applying the procedure specified by the operator to the arguments that are the values of the operands.

92 |

The convention of placing the operator to the left of the operands is known as prefix notation, and it may be somewhat confusing at first because it departs significantly from the customary mathematical convention. Prefix notation has several advantages, however. One of them is that it can accommodate procedures that may take an arbitrary number of arguments, as in the following examples:

93 | (+ 21 35 12 7) 94 | 75 95 | (* 25 4 12) 96 | 1200 97 |

No ambiguity can arise, because the operator is always the leftmost element and the entire combination is delimited by the parentheses.

98 |

A second advantage of prefix notation is that it extends in a straightforward way to allow combinations to be nested, that is, to have combinations whose elements are themselves combinations:

99 | (+ (* 3 5) (- 10 6)) 100 | 19 101 |

There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as

102 | (+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))57 103 |

which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form

104 | (+ (* 3 105 | (+ (* 2 4) 106 | (+ 3 5))) 107 | (+ (- 10 7) 108 | 6))57 109 |

following a formatting convention known as pretty-printing, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.

Lisp systems typically provide features to aid the user in formatting expressions. Two especially useful features are one that automatically indents to the proper pretty-print position whenever a new line is started and one that highlights the matching left parenthesis whenever a right parenthesis is typed.

110 |

111 |

Even with complex expressions, the interpreter always operates in the same basic cycle: It reads an expression from the terminal, evaluates the expression, and prints the result. This mode of operation is often expressed by saying that the interpreter runs in a read-eval-print loop. Observe in particular that it is not necessary to explicitly instruct the interpreter to print the value of the expression.

Lisp obeys the convention that every expression has a value. This convention, together with the old reputation of Lisp as an inefficient language, is the source of the quip by Alan Perlis (paraphrasing Oscar Wilde) that "Lisp programmers know the value of everything but the cost of nothing."

112 |

113 |
114 |
115 |

A critical aspect of a programming language is the means it provides for using names to refer to computational objects. We say that the name identifies a variable whose value is the object.

116 |

In the Scheme dialect of Lisp, we name things with define. Typing

117 | (define size 2)size2 118 |

causes the interpreter to associate the value 2 with the name size.

In this book, we do not show the interpreter's response to evaluating definitions, since this is highly implementation-dependent.

119 | Once the name size has been associated with the number 2, we can refer to the value 2 by name:

120 | (define size 2)size 121 | 2 122 | (define size 2)(* 5 size) 123 | 10 124 |

Here are further examples of the use of define:

125 | (define pi 3.14159) 126 | (define radius 10) 127 | (* pi (* radius radius)) 128 | 314.159 129 | (define pi 3.14159) 130 | (define radius 10)(define circumference (* 2 pi radius)) 131 | circumference 132 | 62.8318 133 |

Define is our language's simplest means of abstraction, for it allows us to use simple names to refer to the results of compound operations, such as the circumference computed above. In general, computational objects may have very complex structures, and it would be extremely inconvenient to have to remember and repeat their details each time we want to use them. Indeed, complex programs are constructed by building, step by step, computational objects of increasing complexity. The interpreter makes this step-by-step program construction particularly convenient because name-object associations can be created incrementally in successive interactions. This feature encourages the incremental development and testing of programs and is largely responsible for the fact that a Lisp program usually consists of a large number of relatively simple procedures.

134 |

It should be clear that the possibility of associating values with symbols and later retrieving them means that the interpreter must maintain some sort of memory that keeps track of the name-object pairs. This memory is called the environment (more precisely the global environment, since we will see later that a computation may involve a number of different environments).

Chapter 3 will show that this notion of environment is crucial, both for understanding how the interpreter works and for implementing interpreters.

135 |

136 |
137 |
138 |

One of our goals in this chapter is to isolate issues about thinking procedurally. As a case in point, let us consider that, in evaluating combinations, the interpreter is itself following a procedure.

139 |
    140 |
  • To evaluate a combination, do the following:
  • 141 |
142 |

1. Evaluate the subexpressions of the combination.

143 |

2. Apply the procedure that is the value of the leftmost subexpression (the operator) to the arguments that are the values of the other subexpressions (the operands).

144 |

Even this simple rule illustrates some important points about processes in general. First, observe that the first step dictates that in order to accomplish the evaluation process for a combination we must first perform the evaluation process on each element of the combination. Thus, the evaluation rule is recursive in nature; that is, it includes, as one of its steps, the need to invoke the rule itself.

It may seem strange that the evaluation rule says, as part of the first step, that we should evaluate the leftmost element of a combination, since at this point that can only be an operator such as + or * representing a built-in primitive procedure such as addition or multiplication. We will see later that it is useful to be able to work with combinations whose operators are themselves compound expressions.

145 |

146 |

Notice how succinctly the idea of recursion can be used to express what, in the case of a deeply nested combination, would otherwise be viewed as a rather complicated process. For example, evaluating

147 | (* (+ 2 (* 4 6)) 148 | (+ 3 5 7))390 149 |

requires that the evaluation rule be applied to four different combinations. We can obtain a picture of this process by representing the combination in the form of a tree, as shown in figure 1.1. Each combination is represented by a node with branches corresponding to the operator and the operands of the combination stemming from it. The terminal nodes (that is, nodes with no branches stemming from them) represent either operators or numbers. Viewing evaluation in terms of the tree, we can imagine that the values of the operands percolate upward, starting from the terminal nodes and then combining at higher and higher levels. In general, we shall see that recursion is a very powerful technique for dealing with hierarchical, treelike objects. In fact, the "percolate values upward" form of the evaluation rule is an example of a general kind of process known as tree accumulation.

150 | 151 |
Tree representation, showing the value of each subcombination.
152 |

Next, observe that the repeated application of the first step brings us to the point where we need to evaluate, not combinations, but primitive expressions such as numerals, built-in operators, or other names. We take care of the primitive cases by stipulating that

153 |
    154 |
  • the values of numerals are the numbers that they name,
  • 155 |
  • the values of built-in operators are the machine instruction sequences that carry out the corresponding operations, and
  • 156 |
  • the values of other names are the objects associated with those names in the environment.
  • 157 |
158 |

We may regard the second rule as a special case of the third one by stipulating that symbols such as + and * are also included in the global environment, and are associated with the sequences of machine instructions that are their "values." The key point to notice is the role of the environment in determining the meaning of the symbols in expressions. In an interactive language such as Lisp, it is meaningless to speak of the value of an expression such as (+ x 1) without specifying any information about the environment that would provide a meaning for the symbol x (or even for the symbol +). As we shall see in chapter 3, the general notion of the environment as providing a context in which evaluation takes place will play an important role in our understanding of program execution.

159 |

Notice that the evaluation rule given above does not handle definitions. For instance, evaluating (define x 3) does not apply define to two arguments, one of which is the value of the symbol x and the other of which is 3, since the purpose of the define is precisely to associate x with a value. (That is, (define x 3) is not a combination.)

160 |

Such exceptions to the general evaluation rule are called special forms. Define is the only example of a special form that we have seen so far, but we will meet others shortly. Each special form has its own evaluation rule. The various kinds of expressions (each with its associated evaluation rule) constitute the syntax of the programming language. In comparison with most other programming languages, Lisp has a very simple syntax; that is, the evaluation rule for expressions can be described by a simple general rule together with specialized rules for a small number of special forms.

Special syntactic forms that are simply convenient alternative surface structures for things that can be written in more uniform ways are sometimes called syntactic sugar, to use a phrase coined by Peter Landin. In comparison with users of other languages, Lisp programmers, as a rule, are less concerned with matters of syntax. (By contrast, examine any Pascal manual and notice how much of it is devoted to descriptions of syntax.) This disdain for syntax is due partly to the flexibility of Lisp, which makes it easy to change surface syntax, and partly to the observation that many "convenient" syntactic constructs, which make the language less uniform, end up causing more trouble than they are worth when programs become large and complex. In the words of Alan Perlis, "Syntactic sugar causes cancer of the semicolon."

161 |

162 |
163 |
164 |

We have identified in Lisp some of the elements that must appear in any powerful programming language:

165 |
    166 |
  • Numbers and arithmetic operations are primitive data and procedures.
  • 167 |
  • Nesting of combinations provides a means of combining operations.
  • 168 |
  • Definitions that associate names with values provide a limited means of abstraction.
  • 169 |
170 |

Now we will learn about procedure definitions, a much more powerful abstraction technique by which a compound operation can be given a name and then referred to as a unit.

171 |

We begin by examining how to express the idea of "squaring." We might say, "To square something, multiply it by itself." This is expressed in our language as

172 | (define (square x) (* x x))(square 3)9 173 |

We can understand this in the following way:

174 | (define (square x) (* x x)) 175 | To square something, multiply it by itself. 176 |

We have here a compound procedure, which has been given the name square. The procedure represents the operation of multiplying something by itself. The thing to be multiplied is given a local name, x, which plays the same role that a pronoun plays in natural language. Evaluating the definition creates this compound procedure and associates it with the name square.

Observe that there are two different operations being combined here: we are creating the procedure, and we are giving it the name square. It is possible, indeed important, to be able to separate these two notions -- to create procedures without naming them, and to give names to procedures that have already been created. We will see how to do this in section 1.3.2.

177 |

178 |

The general form of a procedure definition is

179 | (define (<name> <formal parameters>) <body>) 180 |

The <name> is a symbol to be associated with the procedure definition in the environment.

Throughout this book, we will describe the general syntax of expressions by using symbols delimited by angle brackets -- e.g., <name> -- to denote the "slots" in the expression to be filled in when such an expression is actually used.

181 | The <formal parameters> are the names used within the body of the procedure to refer to the corresponding arguments of the procedure. The <body> is an expression that will yield the value of the procedure application when the formal parameters are replaced by the actual arguments to which the procedure is applied.

More generally, the body of the procedure can be a sequence of expressions. In this case, the interpreter evaluates each expression in the sequence in turn and returns the value of the final expression as the value of the procedure application.

182 |
The <name> and the <formal parameters> are grouped within parentheses, just as they would be in an actual call to the procedure being defined.

183 |

Having defined square, we can now use it:

184 | (define (square x) (* x x))(square 21) 185 | 441 186 | (define (square x) (* x x))(square (+ 2 5)) 187 | 49 188 | (define (square x) (* x x))(square (square 3)) 189 | 81 190 |

We can also use square as a building block in defining other procedures. For example, x2 + y2 can be expressed as

191 | (+ (square x) (square y)) 192 |

We can easily define a procedure sum-of-squares that, given any two numbers as arguments, produces the sum of their squares:

193 | (define (square x) (* x x))(define (sum-of-squares x y) 194 | (+ (square x) (square y))) 195 | 196 | (sum-of-squares 3 4) 197 | 25 198 |

Now we can use sum-of-squares as a building block in constructing further procedures:

199 | (define (square x) (* x x)) 200 | (define (sum-of-squares x y) 201 | (+ (square x) (square y)))(define (f a) 202 | (sum-of-squares (+ a 1) (* a 2))) 203 | 204 | (f 5) 205 | 136 206 |

Compound procedures are used in exactly the same way as primitive procedures. Indeed, one could not tell by looking at the definition of sum-of-squares given above whether square was built into the interpreter, like + and *, or defined as a compound procedure.

207 |
208 |
209 |

To evaluate a combination whose operator names a compound procedure, the interpreter follows much the same process as for combinations whose operators name primitive procedures, which we described in section 1.1.3. That is, the interpreter evaluates the elements of the combination and applies the procedure (which is the value of the operator of the combination) to the arguments (which are the values of the operands of the combination).

210 |

We can assume that the mechanism for applying primitive procedures to arguments is built into the interpreter. For compound procedures, the application process is as follows:

211 |
    212 |
  • To apply a compound procedure to arguments, evaluate the body of the procedure with each formal parameter replaced by the corresponding argument.
  • 213 |
214 |

To illustrate this process, let's evaluate the combination

215 | (f 5) 216 |

where f is the procedure defined in section 1.1.4. We begin by retrieving the body of f:

217 | (sum-of-squares (+ a 1) (* a 2)) 218 |

Then we replace the formal parameter a by the argument 5:

219 | (sum-of-squares (+ 5 1) (* 5 2)) 220 |

Thus the problem reduces to the evaluation of a combination with two operands and an operator sum-of-squares. Evaluating this combination involves three subproblems. We must evaluate the operator to get the procedure to be applied, and we must evaluate the operands to get the arguments. Now (+ 5 1) produces 6 and (* 5 2) produces 10, so we must apply the sum-of-squares procedure to 6 and 10. These values are substituted for the formal parameters x and y in the body of sum-of-squares, reducing the expression to

221 | (+ (square 6) (square 10)) 222 |

If we use the definition of square, this reduces to

223 | (+ (* 6 6) (* 10 10)) 224 |

which reduces by multiplication to

225 | (+ 36 100) 226 |

and finally to

227 | 136 228 |

The process we have just described is called the substitution model for procedure application. It can be taken as a model that determines the "meaning" of procedure application, insofar as the procedures in this chapter are concerned. However, there are two points that should be stressed:

229 |
    230 |
  • The purpose of the substitution is to help us think about procedure application, not to provide a description of how the interpreter really works. Typical interpreters do not evaluate procedure applications by manipulating the text of a procedure to substitute values for the formal parameters. In practice, the "substitution" is accomplished by using a local environment for the formal parameters. We will discuss this more fully in chapters 3 and 4 when we examine the implementation of an interpreter in detail.
  • 231 |
  • Over the course of this book, we will present a sequence of increasingly elaborate models of how interpreters work, culminating with a complete implementation of an interpreter and compiler in chapter 5. The substitution model is only the first of these models -- a way to get started thinking formally about the evaluation process. In general, when modeling phenomena in science and engineering, we begin with simplified, incomplete models. As we examine things in greater detail, these simple models become inadequate and must be replaced by more refined models. The substitution model is no exception. In particular, when we address in chapter 3 the use of procedures with "mutable data," we will see that the substitution model breaks down and must be replaced by a more complicated model of procedure application.

    Despite the simplicity of the substitution idea, it turns out to be surprisingly complicated to give a rigorous mathematical definition of the substitution process. The problem arises from the possibility of confusion between the names used for the formal parameters of a procedure and the (possibly identical) names used in the expressions to which the procedure may be applied. Indeed, there is a long history of erroneous definitions of substitution in the literature of logic and programming semantics. See Stoy 1977 for a careful discussion of substitution.

    232 |
  • 233 |
234 |

According to the description of evaluation given in section 1.1.3, the interpreter first evaluates the operator and operands and then applies the resulting procedure to the resulting arguments. This is not the only way to perform evaluation. An alternative evaluation model would not evaluate the operands until their values were needed. Instead it would first substitute operand expressions for parameters until it obtained an expression involving only primitive operators, and would then perform the evaluation. If we used this method, the evaluation of

235 | (f 5) 236 |

would proceed according to the sequence of expansions

237 | (sum-of-squares (+ 5 1) (* 5 2)) 238 | 239 | (+ (square (+ 5 1)) (square (* 5 2)) ) 240 | 241 | (+ (* (+ 5 1) (+ 5 1)) (* (* 5 2) (* 5 2))) 242 |

followed by the reductions

243 | (+ (* 6 6) (* 10 10)) 244 | 245 | (+ 36 100) 246 | 247 | 136 248 |

This gives the same answer as our previous evaluation model, but the process is different. In particular, the evaluations of (+ 5 1) and (* 5 2) are each performed twice here, corresponding to the reduction of the expression

249 | (* x x) 250 |

with x replaced respectively by (+ 5 1) and (* 5 2).

251 |

This alternative "fully expand and then reduce" evaluation method is known as normal-order evaluation, in contrast to the "evaluate the arguments and then apply" method that the interpreter actually uses, which is called applicative-order evaluation. It can be shown that, for procedure applications that can be modeled using substitution (including all the procedures in the first two chapters of this book) and that yield legitimate values, normal-order and applicative-order evaluation produce the same value. (See exercise 1.5 for an instance of an "illegitimate" value where normal-order and applicative-order evaluation do not give the same result.)

252 |

Lisp uses applicative-order evaluation, partly because of the additional efficiency obtained from avoiding multiple evaluations of expressions such as those illustrated with (+ 5 1) and (* 5 2) above and, more significantly, because normal-order evaluation becomes much more complicated to deal with when we leave the realm of procedures that can be modeled by substitution. On the other hand, normal-order evaluation can be an extremely valuable tool, and we will investigate some of its implications in chapters 3 and 4.

In chapter 3 we will introduce stream processing, which is a way of handling apparently "infinite" data structures by incorporating a limited form of normal-order evaluation. In section 4.2 we will modify the Scheme interpreter to produce a normal-order variant of Scheme.

253 |

254 |
255 |
256 |
257 |

The expressive power of the class of procedures that we can define at this point is very limited, because we have no way to make tests and to perform different operations depending on the result of a test. For instance, we cannot define a procedure that computes the absolute value of a number by testing whether the number is positive, negative, or zero and taking different actions in the different cases according to the rule

258 | 259 | 260 |

This construct is called a case analysis, and there is a special form in Lisp for notating such a case analysis. It is called cond (which stands for "conditional"), and it is used as follows:

261 | (define (abs x) 262 | (cond ((> x 0) x) 263 | ((= x 0) 0) 264 | ((< x 0) (- x))))(abs -1)1 265 |

The general form of a conditional expression is

266 | (cond (<p1> <e1>) 267 | (<p2> <e2>) 268 | 269 | (<pn> <en>)) 270 |

consisting of the symbol cond followed by parenthesized pairs of expressions (<p> <e>) called clauses. The first expression in each pair is a predicate -- that is, an expression whose value is interpreted as either true or false.

"Interpreted as either true or false" means this: In Scheme, there are two distinguished values that are denoted by the constants #t and #f. When the interpreter checks a predicate's value, it interprets #f as false. Any other value is treated as true. (Thus, providing #t is logically unnecessary, but it is convenient.) In this book we will use names true and false, which are associated with the values #t and #f respectively.

271 |

272 |

Conditional expressions are evaluated as follows. The predicate <p1> is evaluated first. If its value is false, then <p2> is evaluated. If <p2>'s value is also false, then <p3> is evaluated. This process continues until a predicate is found whose value is true, in which case the interpreter returns the value of the corresponding consequent expression <e> of the clause as the value of the conditional expression. If none of the <p>'s is found to be true, the value of the cond is undefined.

273 |

The word predicate is used for procedures that return true or false, as well as for expressions that evaluate to true or false. The absolute-value procedure abs makes use of the primitive predicates >, <, and =.

Abs also uses the "minus" operator -, which, when used with a single operand, as in (- x), indicates negation.

274 | These take two numbers as arguments and test whether the first number is, respectively, greater than, less than, or equal to the second number, returning true or false accordingly.

275 |

Another way to write the absolute-value procedure is

276 | (define (abs x) 277 | (cond ((< x 0) (- x)) 278 | (else x)))(abs -1)1 279 |

which could be expressed in English as "If x is less than zero return - x; otherwise return x." Else is a special symbol that can be used in place of the <p> in the final clause of a cond. This causes the cond to return as its value the value of the corresponding <e> whenever all previous clauses have been bypassed. In fact, any expression that always evaluates to a true value could be used as the <p> here.

280 |

Here is yet another way to write the absolute-value procedure:

281 | (define (abs x) 282 | (if (< x 0) 283 | (- x) 284 | x))(abs -1)1 285 |

This uses the special form if, a restricted type of conditional that can be used when there are precisely two cases in the case analysis. The general form of an if expression is

286 | (if <predicate> <consequent> <alternative>) 287 |

To evaluate an if expression, the interpreter starts by evaluating the <predicate> part of the expression. If the <predicate> evaluates to a true value, the interpreter then evaluates the <consequent> and returns its value. Otherwise it evaluates the <alternative> and returns its value.

A minor difference between if and cond is that the <e> part of each cond clause may be a sequence of expressions. If the corresponding <p> is found to be true, the expressions <e> are evaluated in sequence and the value of the final expression in the sequence is returned as the value of the cond. In an if expression, however, the <consequent> and <alternative> must be single expressions.

288 |

289 |

In addition to primitive predicates such as <, =, and >, there are logical composition operations, which enable us to construct compound predicates. The three most frequently used are these:

290 |
    291 |
  • (and <e1> ... <en>) The interpreter evaluates the expressions <e> one at a time, in left-to-right order. If any <e> evaluates to false, the value of the and expression is false, and the rest of the <e>'s are not evaluated. If all <e>'s evaluate to true values, the value of the and expression is the value of the last one.
  • 292 |
  • (or <e1> ... <en>) The interpreter evaluates the expressions <e> one at a time, in left-to-right order. If any <e> evaluates to a true value, that value is returned as the value of the or expression, and the rest of the <e>'s are not evaluated. If all <e>'s evaluate to false, the value of the or expression is false.
  • 293 |
  • (not <e>) The value of a not expression is true when the expression <e> evaluates to false, and false otherwise.
  • 294 |
295 |

Notice that and and or are special forms, not procedures, because the subexpressions are not necessarily all evaluated. Not is an ordinary procedure.

296 |

As an example of how these are used, the condition that a number x be in the range 5 < x < 10 may be expressed as

297 | (and (> x 5) (< x 10)) 298 |

As another example, we can define a predicate to test whether one number is greater than or equal to another as

299 | (define (>= x y) 300 | (or (> x y) (= x y)))(>= 2 2)#t 301 |

or alternatively as

302 | (define (>= x y) 303 | (not (< x y)))(> 2 3)#f 304 | 305 |

Below is a sequence of expressions. What is the result printed by the interpreter in response to each expression? Assume that the sequence is to be evaluated in the order in which it is presented.

306 | 10 307 | (+ 5 3 4) 308 | (- 9 1) 309 | (/ 6 2) 310 | (+ (* 2 4) (- 4 6)) 311 | (define a 3) 312 | (define b (+ a 1)) 313 | (+ a b (* a b)) 314 | (= a b) 315 | (if (and (> b a) (< b (* a b))) 316 | b 317 | a) 318 | (cond ((= a 4) 6) 319 | ((= b 4) (+ 6 7 a)) 320 | (else 25)) 321 | (+ 2 (if (> b a) b a)) 322 | (* (cond ((> a b) a) 323 | ((< a b) b) 324 | (else -1)) 325 | (+ a 1)) 326 |
327 | 328 |

Translate the following expression into prefix form

329 | 330 | 331 |
332 | 333 |

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

334 |
335 | 336 |

Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:

337 | (define (a-plus-abs-b a b) 338 | ((if (> b 0) + -) a b)) 339 |
340 | 341 |

Ben Bitdiddle has invented a test to determine whether the interpreter he is faced with is using applicative-order evaluation or normal-order evaluation. He defines the following two procedures:

342 | (define (p) (p)) 343 | 344 | (define (test x y) 345 | (if (= x 0) 346 | 0 347 | y)) 348 |

Then he evaluates the expression

349 | (test 0 (p)) 350 |

What behavior will Ben observe with an interpreter that uses applicative-order evaluation? What behavior will he observe with an interpreter that uses normal-order evaluation? Explain your answer. (Assume that the evaluation rule for the special form if is the same whether the interpreter is using normal or applicative order: The predicate expression is evaluated first, and the result determines whether to evaluate the consequent or the alternative expression.)

351 |
352 |
353 |
354 |

Procedures, as introduced above, are much like ordinary mathematical functions. They specify a value that is determined by one or more parameters. But there is an important difference between mathematical functions and computer procedures. Procedures must be effective.

355 |

As a case in point, consider the problem of computing square roots. We can define the square-root function as

356 | 357 | 358 |

This describes a perfectly legitimate mathematical function. We could use it to recognize whether one number is the square root of another, or to derive facts about square roots in general. On the other hand, the definition does not describe a procedure. Indeed, it tells us almost nothing about how to actually find the square root of a given number. It will not help matters to rephrase this definition in pseudo-Lisp:

359 | (define (sqrt x) 360 | (the y (and (>= y 0) 361 | (= (square y) x)))) 362 |

This only begs the question.

363 |

The contrast between function and procedure is a reflection of the general distinction between describing properties of things and describing how to do things, or, as it is sometimes referred to, the distinction between declarative knowledge and imperative knowledge. In mathematics we are usually concerned with declarative (what is) descriptions, whereas in computer science we are usually concerned with imperative (how to) descriptions.

Declarative and imperative descriptions are intimately related, as indeed are mathematics and computer science. For instance, to say that the answer produced by a program is "correct" is to make a declarative statement about the program. There is a large amount of research aimed at establishing techniques for proving that programs are correct, and much of the technical difficulty of this subject has to do with negotiating the transition between imperative statements (from which programs are constructed) and declarative statements (which can be used to deduce things). In a related vein, an important current area in programming-language design is the exploration of so-called very high-level languages, in which one actually programs in terms of declarative statements. The idea is to make interpreters sophisticated enough so that, given "what is" knowledge specified by the programmer, they can generate "how to" knowledge automatically. This cannot be done in general, but there are important areas where progress has been made. We shall revisit this idea in chapter 4.

364 |

365 |

How does one compute square roots? The most common way is to use Newton's method of successive approximations, which says that whenever we have a guess y for the value of the square root of a number x, we can perform a simple manipulation to get a better guess (one closer to the actual square root) by averaging y with x/y.

This square-root algorithm is actually a special case of Newton's method, which is a general technique for finding roots of equations. The square-root algorithm itself was developed by Heron of Alexandria in the first century A.D. We will see how to express the general Newton's method as a Lisp procedure in section 1.3.4.

366 | For example, we can compute the square root of 2 as follows. Suppose our initial guess is 1:

367 | 368 | 370 | 372 | 374 | 375 |
Guess Quotient Average
1 (2/1) = 2 369 | ((2 + 1)/2) = 1.5
1.5 (2/1.5) = 1.3333 371 | ((1.3333 + 1.5)/2) = 1.4167
1.4167 (2/1.4167) = 1.4118 373 | ((1.4167 + 1.4118)/2) = 1.4142
1.4142 ......

Continuing this process, we obtain better and better approximations to the square root.

376 |

Now let's formalize the process in terms of procedures. We start with a value for the radicand (the number whose square root we are trying to compute) and a value for the guess. If the guess is good enough for our purposes, we are done; if not, we must repeat the process with an improved guess. We write this basic strategy as a procedure:

377 | (define (sqrt-iter guess x) 378 | (if (good-enough? guess x) 379 | guess 380 | (sqrt-iter (improve guess x) 381 | x))) 382 |

A guess is improved by averaging it with the quotient of the radicand and the old guess:

383 | (define (improve guess x) 384 | (average guess (/ x guess))) 385 |

where

386 | (define (average x y) 387 | (/ (+ x y) 2))(average 10 20)15 388 |

We also have to say what we mean by "good enough." The following will do for illustration, but it is not really a very good test. (See exercise 1.7.) The idea is to improve the answer until it is close enough so that its square differs from the radicand by less than a predetermined tolerance (here 0.001):

We will usually give predicates names ending with question marks, to help us remember that they are predicates. This is just a stylistic convention. As far as the interpreter is concerned, the question mark is just an ordinary character.

389 |

390 | (define (square x) (* x x)) 391 | (define (abs x) 392 | (if (< x 0) 393 | (- x) 394 | x))(define (good-enough? guess x) 395 | (< (abs (- (square guess) x)) 0.001))(good-enough? 2.9999 9)#t 396 |

Finally, we need a way to get started. For instance, we can always guess that the square root of any number is 1:

397 | (define (square x) (* x x)) 398 | (define (abs x) 399 | (if (< x 0) 400 | (- x) 401 | x)) 402 | (define (sqrt-iter guess x) 403 | (if (good-enough? guess x) 404 | guess 405 | (sqrt-iter (improve guess x) 406 | x))) 407 | (define (improve guess x) 408 | (average guess (/ x guess))) 409 | (define (average x y) 410 | (/ (+ x y) 2)) 411 | (define (good-enough? guess x) 412 | (< (abs (- (square guess) x)) 0.001))(define (sqrt x) 413 | (sqrt-iter 1.0 x))(sqrt 9)3.00009155413138 414 |

If we type these definitions to the interpreter, we can use sqrt just as we can use any procedure:

415 | (define (square x) (* x x)) 416 | (define (abs x) 417 | (if (< x 0) 418 | (- x) 419 | x)) 420 | (define (sqrt-iter guess x) 421 | (if (good-enough? guess x) 422 | guess 423 | (sqrt-iter (improve guess x) 424 | x))) 425 | (define (improve guess x) 426 | (average guess (/ x guess))) 427 | (define (average x y) 428 | (/ (+ x y) 2)) 429 | (define (good-enough? guess x) 430 | (< (abs (- (square guess) x)) 0.001)) 431 | (define (sqrt x) 432 | (sqrt-iter 1.0 x))(sqrt 9) 433 | 3.00009155413138 434 | (define (square x) (* x x)) 435 | (define (abs x) 436 | (if (< x 0) 437 | (- x) 438 | x)) 439 | (define (sqrt-iter guess x) 440 | (if (good-enough? guess x) 441 | guess 442 | (sqrt-iter (improve guess x) 443 | x))) 444 | (define (improve guess x) 445 | (average guess (/ x guess))) 446 | (define (average x y) 447 | (/ (+ x y) 2)) 448 | (define (good-enough? guess x) 449 | (< (abs (- (square guess) x)) 0.001)) 450 | (define (sqrt x) 451 | (sqrt-iter 1.0 x))(sqrt (+ 100 37)) 452 | 11.704699917758145 453 | (define (square x) (* x x)) 454 | (define (abs x) 455 | (if (< x 0) 456 | (- x) 457 | x)) 458 | (define (sqrt-iter guess x) 459 | (if (good-enough? guess x) 460 | guess 461 | (sqrt-iter (improve guess x) 462 | x))) 463 | (define (improve guess x) 464 | (average guess (/ x guess))) 465 | (define (average x y) 466 | (/ (+ x y) 2)) 467 | (define (good-enough? guess x) 468 | (< (abs (- (square guess) x)) 0.001)) 469 | (define (sqrt x) 470 | (sqrt-iter 1.0 x))(sqrt (+ (sqrt 2) (sqrt 3))) 471 | 1.7739279023207892 472 | (define (square x) (* x x)) 473 | (define (abs x) 474 | (if (< x 0) 475 | (- x) 476 | x)) 477 | (define (sqrt-iter guess x) 478 | (if (good-enough? guess x) 479 | guess 480 | (sqrt-iter (improve guess x) 481 | x))) 482 | (define (improve guess x) 483 | (average guess (/ x guess))) 484 | (define (average x y) 485 | (/ (+ x y) 2)) 486 | (define (good-enough? guess x) 487 | (< (abs (- (square guess) x)) 0.001)) 488 | (define (sqrt x) 489 | (sqrt-iter 1.0 x))(square (sqrt 1000)) 490 | 1000.000369924366 491 |

The sqrt program also illustrates that the simple procedural language we have introduced so far is sufficient for writing any purely numerical program that one could write in, say, C or Pascal. This might seem surprising, since we have not included in our language any iterative (looping) constructs that direct the computer to do something over and over again. Sqrt-iter, on the other hand, demonstrates how iteration can be accomplished using no special construct other than the ordinary ability to call a procedure.

Readers who are worried about the efficiency issues involved in using procedure calls to implement iteration should note the remarks on "tail recursion" in section 1.2.1.

492 |

493 | 494 |

Alyssa P. Hacker doesn't see why if needs to be provided as a special form. "Why can't I just define it as an ordinary procedure in terms of cond?" she asks. Alyssa's friend Eva Lu Ator claims this can indeed be done, and she defines a new version of if:

495 | (define (new-if predicate then-clause else-clause) 496 | (cond (predicate then-clause) 497 | (else else-clause))) 498 |

Eva demonstrates the program for Alyssa:

499 | (new-if (= 2 3) 0 5) 500 | 5 501 | (new-if (= 1 1) 0 5) 502 | 0 503 |

Delighted, Alyssa uses new-if to rewrite the square-root program:

504 | (define (sqrt-iter guess x) 505 | (new-if (good-enough? guess x) 506 | guess 507 | (sqrt-iter (improve guess x) 508 | x))) 509 |

What happens when Alyssa attempts to use this to compute square roots? Explain.

510 |
511 | 512 |

The good-enough? test used in computing square roots will not be very effective for finding the square roots of very small numbers. Also, in real computers, arithmetic operations are almost always performed with limited precision. This makes our test inadequate for very large numbers. Explain these statements, with examples showing how the test fails for small and large numbers. An alternative strategy for implementing good-enough? is to watch how guess changes from one iteration to the next and to stop when the change is a very small fraction of the guess. Design a square-root procedure that uses this kind of end test. Does this work better for small and large numbers?

513 |
514 | 515 |

Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value

516 | 517 | 518 |

Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In section 1.3.4 we will see how to implement Newton's method in general as an abstraction of these square-root and cube-root procedures.)

519 |
520 |
521 |
522 |

Sqrt is our first example of a process defined by a set of mutually defined procedures. Notice that the definition of sqrt-iter is recursive; that is, the procedure is defined in terms of itself. The idea of being able to define a procedure in terms of itself may be disturbing; it may seem unclear how such a "circular" definition could make sense at all, much less specify a well-defined process to be carried out by a computer. This will be addressed more carefully in section 1.2. But first let's consider some other important points illustrated by the sqrt example.

523 |

Observe that the problem of computing square roots breaks up naturally into a number of subproblems: how to tell whether a guess is good enough, how to improve a guess, and so on. Each of these tasks is accomplished by a separate procedure. The entire sqrt program can be viewed as a cluster of procedures (shown in figure 1.2) that mirrors the decomposition of the problem into subproblems.

524 | 525 |
Procedural decomposition of the sqrt program.
526 |

The importance of this decomposition strategy is not simply that one is dividing the program into parts. After all, we could take any large program and divide it into parts -- the first ten lines, the next ten lines, the next ten lines, and so on. Rather, it is crucial that each procedure accomplishes an identifiable task that can be used as a module in defining other procedures. For example, when we define the good-enough? procedure in terms of square, we are able to regard the square procedure as a "black box." We are not at that moment concerned with how the procedure computes its result, only with the fact that it computes the square. The details of how the square is computed can be suppressed, to be considered at a later time. Indeed, as far as the good-enough? procedure is concerned, square is not quite a procedure but rather an abstraction of a procedure, a so-called procedural abstraction. At this level of abstraction, any procedure that computes the square is equally good.

527 |

Thus, considering only the values they return, the following two procedures for squaring a number should be indistinguishable. Each takes a numerical argument and produces the square of that number as the value.

It is not even clear which of these procedures is a more efficient implementation. This depends upon the hardware available. There are machines for which the "obvious" implementation is the less efficient one. Consider a machine that has extensive tables of logarithms and antilogarithms stored in a very efficient manner.

528 |

529 | (define (square x) (* x x))(square 3)9 530 | (define (square x) 531 | (exp (double (log x)))) 532 | 533 | (define (double x) (+ x x))(square 3)9 534 |

So a procedure definition should be able to suppress detail. The users of the procedure may not have written the procedure themselves, but may have obtained it from another programmer as a black box. A user should not need to know how the procedure is implemented in order to use it.

535 |

One detail of a procedure's implementation that should not matter to the user of the procedure is the implementer's choice of names for the procedure's formal parameters. Thus, the following procedures should not be distinguishable:

536 | (define (square x) (* x x)) 537 | 538 | (define (square y) (* y y)) 539 |

This principle -- that the meaning of a procedure should be independent of the parameter names used by its author -- seems on the surface to be self-evident, but its consequences are profound. The simplest consequence is that the parameter names of a procedure must be local to the body of the procedure. For example, we used square in the definition of good-enough? in our square-root procedure:

540 | (define (good-enough? guess x) 541 | (< (abs (- (square guess) x)) 0.001)) 542 |

The intention of the author of good-enough? is to determine if the square of the first argument is within a given tolerance of the second argument. We see that the author of good-enough? used the name guess to refer to the first argument and x to refer to the second argument. The argument of square is guess. If the author of square used x (as above) to refer to that argument, we see that the x in good-enough? must be a different x than the one in square. Running the procedure square must not affect the value of x that is used by good-enough?, because that value of x may be needed by good-enough? after square is done computing.

543 |

If the parameters were not local to the bodies of their respective procedures, then the parameter x in square could be confused with the parameter x in good-enough?, and the behavior of good-enough? would depend upon which version of square we used. Thus, square would not be the black box we desired.

544 |

A formal parameter of a procedure has a very special role in the procedure definition, in that it doesn't matter what name the formal parameter has. Such a name is called a bound variable, and we say that the procedure definition binds its formal parameters. The meaning of a procedure definition is unchanged if a bound variable is consistently renamed throughout the definition.

The concept of consistent renaming is actually subtle and difficult to define formally. Famous logicians have made embarrassing errors here.

545 | If a variable is not bound, we say that it is free. The set of expressions for which a binding defines a name is called the scope of that name. In a procedure definition, the bound variables declared as the formal parameters of the procedure have the body of the procedure as their scope.

546 |

In the definition of good-enough? above, guess and x are bound variables but <, -, abs, and square are free. The meaning of good-enough? should be independent of the names we choose for guess and x so long as they are distinct and different from <, -, abs, and square. (If we renamed guess to abs we would have introduced a bug by capturing the variable abs. It would have changed from free to bound.) The meaning of good-enough? is not independent of the names of its free variables, however. It surely depends upon the fact (external to this definition) that the symbol abs names a procedure for computing the absolute value of a number. Good-enough? will compute a different function if we substitute cos for abs in its definition.

547 |
548 |

We have one kind of name isolation available to us so far: The formal parameters of a procedure are local to the body of the procedure. The square-root program illustrates another way in which we would like to control the use of names. The existing program consists of separate procedures:

549 | (define (square x) (* x x)) 550 | (define (abs x) (if (< x 0) (- x) x)) 551 | (define (average x y) (/ (+ x y) 2))(define (sqrt x) 552 | (sqrt-iter 1.0 x)) 553 | (define (sqrt-iter guess x) 554 | (if (good-enough? guess x) 555 | guess 556 | (sqrt-iter (improve guess x) x))) 557 | (define (good-enough? guess x) 558 | (< (abs (- (square guess) x)) 0.001)) 559 | (define (improve guess x) 560 | (average guess (/ x guess)))(sqrt 9)3.00009155413138 561 |

The problem with this program is that the only procedure that is important to users of sqrt is sqrt. The other procedures (sqrt-iter, good-enough?, and improve) only clutter up their minds. They may not define any other procedure called good-enough? as part of another program to work together with the square-root program, because sqrt needs it. The problem is especially severe in the construction of large systems by many separate programmers. For example, in the construction of a large library of numerical procedures, many numerical functions are computed as successive approximations and thus might have procedures named good-enough? and improve as auxiliary procedures. We would like to localize the subprocedures, hiding them inside sqrt so that sqrt could coexist with other successive approximations, each having its own private good-enough? procedure. To make this possible, we allow a procedure to have internal definitions that are local to that procedure. For example, in the square-root problem we can write

562 | (define (square x) (* x x)) 563 | (define (abs x) (if (< x 0) (- x) x)) 564 | (define (average x y) (/ (+ x y) 2))(define (sqrt x) 565 | (define (good-enough? guess x) 566 | (< (abs (- (square guess) x)) 0.001)) 567 | (define (improve guess x) 568 | (average guess (/ x guess))) 569 | (define (sqrt-iter guess x) 570 | (if (good-enough? guess x) 571 | guess 572 | (sqrt-iter (improve guess x) x))) 573 | (sqrt-iter 1.0 x))(sqrt 9)3.00009155413138 574 |

Such nesting of definitions, called block structure, is basically the right solution to the simplest name-packaging problem. But there is a better idea lurking here. In addition to internalizing the definitions of the auxiliary procedures, we can simplify them. Since x is bound in the definition of sqrt, the procedures good-enough?, improve, and sqrt-iter, which are defined internally to sqrt, are in the scope of x. Thus, it is not necessary to pass x explicitly to each of these procedures. Instead, we allow x to be a free variable in the internal definitions, as shown below. Then x gets its value from the argument with which the enclosing procedure sqrt is called. This discipline is called lexical scoping.

Lexical scoping dictates that free variables in a procedure are taken to refer to bindings made by enclosing procedure definitions; that is, they are looked up in the environment in which the procedure was defined. We will see how this works in detail in chapter 3 when we study environments and the detailed behavior of the interpreter.

575 |

576 | (define (square x) (* x x)) 577 | (define (abs x) (if (< x 0) (- x) x)) 578 | (define (average x y) (/ (+ x y) 2))(define (sqrt x) 579 | (define (good-enough? guess) 580 | (< (abs (- (square guess) x)) 0.001)) 581 | (define (improve guess) 582 | (average guess (/ x guess))) 583 | (define (sqrt-iter guess) 584 | (if (good-enough? guess) 585 | guess 586 | (sqrt-iter (improve guess)))) 587 | (sqrt-iter 1.0))(sqrt 9)3.00009155413138 588 |

We will use block structure extensively to help us break up large programs into tractable pieces.

Embedded definitions must come first in a procedure body. The management is not responsible for the consequences of running programs that intertwine definition and use.

589 | The idea of block structure originated with the programming language Algol 60. It appears in most advanced programming languages and is an important tool for helping to organize the construction of large programs.

590 |
591 | 592 |
593 |
594 | 595 |
596 |

We have now considered the elements of programming: We have used primitive arithmetic operations, we have combined these operations, and we have abstracted these composite operations by defining them as compound procedures. But that is not enough to enable us to say that we know how to program. Our situation is analogous to that of someone who has learned the rules for how the pieces move in chess but knows nothing of typical openings, tactics, or strategy. Like the novice chess player, we don't yet know the common patterns of usage in the domain. We lack the knowledge of which moves are worth making (which procedures are worth defining). We lack the experience to predict the consequences of making a move (executing a procedure).

597 |

The ability to visualize the consequences of the actions under consideration is crucial to becoming an expert programmer, just as it is in any synthetic, creative activity. In becoming an expert photographer, for example, one must learn how to look at a scene and know how dark each region will appear on a print for each possible choice of exposure and development conditions. Only then can one reason backward, planning framing, lighting, exposure, and development to obtain the desired effects. So it is with programming, where we are planning the course of action to be taken by a process and where we control the process by means of a program. To become experts, we must learn to visualize the processes generated by various types of procedures. Only after we have developed such a skill can we learn to reliably construct programs that exhibit the desired behavior.

598 |

A procedure is a pattern for the local evolution of a computational process. It specifies how each stage of the process is built upon the previous stage. We would like to be able to make statements about the overall, or global, behavior of a process whose local evolution has been specified by a procedure. This is very difficult to do in general, but we can at least try to describe some typical patterns of process evolution.

599 |

In this section we will examine some common "shapes" for processes generated by simple procedures. We will also investigate the rates at which these processes consume the important computational resources of time and space. The procedures we will consider are very simple. Their role is like that played by test patterns in photography: as oversimplified prototypical patterns, rather than practical examples in their own right.

600 |
601 | 602 |
A linear recursive process for computing 6!.
603 |

We begin by considering the factorial function, defined by

604 | 605 | 606 |

There are many ways to compute factorials. One way is to make use of the observation that n! is equal to n times (n - 1)! for any positive integer n:

607 | 608 | 609 |

Thus, we can compute n! by computing (n - 1)! and multiplying the result by n. If we add the stipulation that 1! is equal to 1, this observation translates directly into a procedure:

610 | (define (factorial n) 611 | (if (= n 1) 612 | 1 613 | (* n (factorial (- n 1)))))(factorial 4)24 614 |

We can use the substitution model of section 1.1.5 to watch this procedure in action computing 6!, as shown in figure 1.3.

615 |

Now let's take a different perspective on computing factorials. We could describe a rule for computing n! by specifying that we first multiply 1 by 2, then multiply the result by 3, then by 4, and so on until we reach n. More formally, we maintain a running product, together with a counter that counts from 1 up to n. We can describe the computation by saying that the counter and the product simultaneously change from one step to the next according to the rule

616 |

product counter · product

617 |

counter counter + 1

618 |

and stipulating that n! is the value of the product when the counter exceeds n.

619 | 620 |
A linear iterative process for computing 6!.
621 |

Once again, we can recast our description as a procedure for computing factorials:

In a real program we would probably use the block structure introduced in the last section to hide the definition of fact-iter:

622 | (define (factorial n) 623 | (define (iter product counter) 624 | (if (> counter n) 625 | product 626 | (iter (* counter product) 627 | (+ counter 1)))) 628 | (iter 1 1))(factorial 4)24 629 |

We avoided doing this here so as to minimize the number of things to think about at once.

630 |

631 | (define (factorial n) 632 | (fact-iter 1 1 n)) 633 | 634 | (define (fact-iter product counter max-count) 635 | (if (> counter max-count) 636 | product 637 | (fact-iter (* counter product) 638 | (+ counter 1) 639 | max-count)))(factorial 4)24 640 |

As before, we can use the substitution model to visualize the process of computing 6!, as shown in figure 1.4.

641 |

Compare the two processes. From one point of view, they seem hardly different at all. Both compute the same mathematical function on the same domain, and each requires a number of steps proportional to n to compute n!. Indeed, both processes even carry out the same sequence of multiplications, obtaining the same sequence of partial products. On the other hand, when we consider the "shapes" of the two processes, we find that they evolve quite differently.

642 |

Consider the first process. The substitution model reveals a shape of expansion followed by contraction, indicated by the arrow in figure 1.3. The expansion occurs as the process builds up a chain of deferred operations (in this case, a chain of multiplications). The contraction occurs as the operations are actually performed. This type of process, characterized by a chain of deferred operations, is called a recursive process. Carrying out this process requires that the interpreter keep track of the operations to be performed later on. In the computation of n!, the length of the chain of deferred multiplications, and hence the amount of information needed to keep track of it, grows linearly with n (is proportional to n), just like the number of steps. Such a process is called a linear recursive process.

643 |

By contrast, the second process does not grow and shrink. At each step, all we need to keep track of, for any n, are the current values of the variables product, counter, and max-count. We call this an iterative process. In general, an iterative process is one whose state can be summarized by a fixed number of state variables, together with a fixed rule that describes how the state variables should be updated as the process moves from state to state and an (optional) end test that specifies conditions under which the process should terminate. In computing n!, the number of steps required grows linearly with n. Such a process is called a linear iterative process.

644 |

The contrast between the two processes can be seen in another way. In the iterative case, the program variables provide a complete description of the state of the process at any point. If we stopped the computation between steps, all we would need to do to resume the computation is to supply the interpreter with the values of the three program variables. Not so with the recursive process. In this case there is some additional "hidden" information, maintained by the interpreter and not contained in the program variables, which indicates "where the process is" in negotiating the chain of deferred operations. The longer the chain, the more information must be maintained.

When we discuss the implementation of procedures on register machines in chapter 5, we will see that any iterative process can be realized "in hardware" as a machine that has a fixed set of registers and no auxiliary memory. In contrast, realizing a recursive process requires a machine that uses an auxiliary data structure known as a stack.

645 |

646 |

In contrasting iteration and recursion, we must be careful not to confuse the notion of a recursive process with the notion of a recursive procedure. When we describe a procedure as recursive, we are referring to the syntactic fact that the procedure definition refers (either directly or indirectly) to the procedure itself. But when we describe a process as following a pattern that is, say, linearly recursive, we are speaking about how the process evolves, not about the syntax of how a procedure is written. It may seem disturbing that we refer to a recursive procedure such as fact-iter as generating an iterative process. However, the process really is iterative: Its state is captured completely by its three state variables, and an interpreter need keep track of only three variables in order to execute the process.

647 |

One reason that the distinction between process and procedure may be confusing is that most implementations of common languages (including Ada, Pascal, and C) are designed in such a way that the interpretation of any recursive procedure consumes an amount of memory that grows with the number of procedure calls, even when the process described is, in principle, iterative. As a consequence, these languages can describe iterative processes only by resorting to special-purpose "looping constructs" such as do, repeat, until, for, and while. The implementation of Scheme we shall consider in chapter 5 does not share this defect. It will execute an iterative process in constant space, even if the iterative process is described by a recursive procedure. An implementation with this property is called tail-recursive. With a tail-recursive implementation, iteration can be expressed using the ordinary procedure call mechanism, so that special iteration constructs are useful only as syntactic sugar.

Tail recursion has long been known as a compiler optimization trick. A coherent semantic basis for tail recursion was provided by Carl Hewitt (1977), who explained it in terms of the "message-passing" model of computation that we shall discuss in chapter 3. Inspired by this, Gerald Jay Sussman and Guy Lewis Steele Jr. (see Steele 1975) constructed a tail-recursive interpreter for Scheme. Steele later showed how tail recursion is a consequence of the natural way to compile procedure calls (Steele 1977). The IEEE standard for Scheme requires that Scheme implementations be tail-recursive.

648 |

649 | 650 |

Each of the following two procedures defines a method for adding two positive integers in terms of the procedures inc, which increments its argument by 1, and dec, which decrements its argument by 1.

651 | (define (+ a b) 652 | (if (= a 0) 653 | b 654 | (inc (+ (dec a) b)))) 655 | (define (+ a b) 656 | (if (= a 0) 657 | b 658 | (+ (dec a) (inc b)))) 659 |

Using the substitution model, illustrate the process generated by each procedure in evaluating (+ 4 5). Are these processes iterative or recursive?

660 |
661 | 662 |

The following procedure computes a mathematical function called Ackermann's function.

663 | (define (A x y) 664 | (cond ((= y 0) 0) 665 | ((= x 0) (* 2 y)) 666 | ((= y 1) 2) 667 | (else (A (- x 1) 668 | (A x (- y 1)))))) 669 |

What are the values of the following expressions?

670 | (A 1 10) 671 | 672 | (A 2 4) 673 | 674 | (A 3 3) 675 |

Consider the following procedures, where A is the procedure defined above:

676 | (define (f n) (A 0 n)) 677 | 678 | (define (g n) (A 1 n)) 679 | 680 | (define (h n) (A 2 n)) 681 | 682 | (define (k n) (* 5 n n)) 683 |

Give concise mathematical definitions for the functions computed by the procedures f, g, and h for positive integer values of n. For example, (k n) computes 5n2.

684 |
685 |
686 |
687 |

Another common pattern of computation is called tree recursion. As an example, consider computing the sequence of Fibonacci numbers, in which each number is the sum of the preceding two:

688 | 689 | 690 |

In general, the Fibonacci numbers can be defined by the rule

691 | 692 | 693 |

We can immediately translate this definition into a recursive procedure for computing Fibonacci numbers:

694 | (define (fib n) 695 | (cond ((= n 0) 0) 696 | ((= n 1) 1) 697 | (else (+ (fib (- n 1)) 698 | (fib (- n 2))))))(fib 6)8 699 | 700 |
The tree-recursive process generated in computing (fib 5).
701 |

Consider the pattern of this computation. To compute (fib 5), we compute (fib 4) and (fib 3). To compute (fib 4), we compute (fib 3) and (fib 2). In general, the evolved process looks like a tree, as shown in figure 1.5. Notice that the branches split into two at each level (except at the bottom); this reflects the fact that the fib procedure calls itself twice each time it is invoked.

702 |

This procedure is instructive as a prototypical tree recursion, but it is a terrible way to compute Fibonacci numbers because it does so much redundant computation. Notice in figure 1.5 that the entire computation of (fib 3) -- almost half the work -- is duplicated. In fact, it is not hard to show that the number of times the procedure will compute (fib 1) or (fib 0) (the number of leaves in the above tree, in general) is precisely Fib(n + 1). To get an idea of how bad this is, one can show that the value of Fib(n) grows exponentially with n. More precisely (see exercise 1.13), Fib(n) is the closest integer to n /5, where

703 | 704 | 705 |

is the golden ratio, which satisfies the equation

706 | 707 | 708 |

Thus, the process uses a number of steps that grows exponentially with the input. On the other hand, the space required grows only linearly with the input, because we need keep track only of which nodes are above us in the tree at any point in the computation. In general, the number of steps required by a tree-recursive process will be proportional to the number of nodes in the tree, while the space required will be proportional to the maximum depth of the tree.

709 |

We can also formulate an iterative process for computing the Fibonacci numbers. The idea is to use a pair of integers a and b, initialized to Fib(1) = 1 and Fib(0) = 0, and to repeatedly apply the simultaneous transformations

710 | 711 | 712 |

It is not hard to show that, after applying this transformation n times, a and b will be equal, respectively, to Fib(n + 1) and Fib(n). Thus, we can compute Fibonacci numbers iteratively using the procedure

713 | (define (fib n) 714 | (fib-iter 1 0 n)) 715 | 716 | (define (fib-iter a b count) 717 | (if (= count 0) 718 | b 719 | (fib-iter (+ a b) a (- count 1))))(fib 6)8 720 |

This second method for computing Fib(n) is a linear iteration. The difference in number of steps required by the two methods -- one linear in n, one growing as fast as Fib(n) itself -- is enormous, even for small inputs.

721 |

One should not conclude from this that tree-recursive processes are useless. When we consider processes that operate on hierarchically structured data rather than numbers, we will find that tree recursion is a natural and powerful tool.

An example of this was hinted at in section 1.1.3: The interpreter itself evaluates expressions using a tree-recursive process.

722 | But even in numerical operations, tree-recursive processes can be useful in helping us to understand and design programs. For instance, although the first fib procedure is much less efficient than the second one, it is more straightforward, being little more than a translation into Lisp of the definition of the Fibonacci sequence. To formulate the iterative algorithm required noticing that the computation could be recast as an iteration with three state variables.

723 |

It takes only a bit of cleverness to come up with the iterative Fibonacci algorithm. In contrast, consider the following problem: How many different ways can we make change of $ 1.00, given half-dollars, quarters, dimes, nickels, and pennies? More generally, can we write a procedure to compute the number of ways to change any given amount of money?

724 |

This problem has a simple solution as a recursive procedure. Suppose we think of the types of coins available as arranged in some order. Then the following relation holds:

725 |

The number of ways to change amount a using n kinds of coins equals

726 |
    727 |
  • the number of ways to change amount a using all but the first kind of coin, plus
  • 728 |
  • the number of ways to change amount a - d using all n kinds of coins, where d is the denomination of the first kind of coin.
  • 729 |
730 |

To see why this is true, observe that the ways to make change can be divided into two groups: those that do not use any of the first kind of coin, and those that do. Therefore, the total number of ways to make change for some amount is equal to the number of ways to make change for the amount without using any of the first kind of coin, plus the number of ways to make change assuming that we do use the first kind of coin. But the latter number is equal to the number of ways to make change for the amount that remains after using a coin of the first kind.

731 |

Thus, we can recursively reduce the problem of changing a given amount to the problem of changing smaller amounts using fewer kinds of coins. Consider this reduction rule carefully, and convince yourself that we can use it to describe an algorithm if we specify the following degenerate cases:

For example, work through in detail how the reduction rule applies to the problem of making change for 10 cents using pennies and nickels.

732 |

733 |
    734 |
  • If a is exactly 0, we should count that as 1 way to make change.
  • 735 |
  • If a is less than 0, we should count that as 0 ways to make change.
  • 736 |
  • If n is 0, we should count that as 0 ways to make change.
  • 737 |
738 |

We can easily translate this description into a recursive procedure:

739 | (define (count-change amount) 740 | (cc amount 5)) 741 | (define (cc amount kinds-of-coins) 742 | (cond ((= amount 0) 1) 743 | ((or (< amount 0) (= kinds-of-coins 0)) 0) 744 | (else (+ (cc amount 745 | (- kinds-of-coins 1)) 746 | (cc (- amount 747 | (first-denomination kinds-of-coins)) 748 | kinds-of-coins))))) 749 | (define (first-denomination kinds-of-coins) 750 | (cond ((= kinds-of-coins 1) 1) 751 | ((= kinds-of-coins 2) 5) 752 | ((= kinds-of-coins 3) 10) 753 | ((= kinds-of-coins 4) 25) 754 | ((= kinds-of-coins 5) 50)))(count-change 100)292 755 |

(The first-denomination procedure takes as input the number of kinds of coins available and returns the denomination of the first kind. Here we are thinking of the coins as arranged in order from largest to smallest, but any order would do as well.) We can now answer our original question about changing a dollar:

756 | (define (count-change amount) 757 | (cc amount 5)) 758 | (define (cc amount kinds-of-coins) 759 | (cond ((= amount 0) 1) 760 | ((or (< amount 0) (= kinds-of-coins 0)) 0) 761 | (else (+ (cc amount 762 | (- kinds-of-coins 1)) 763 | (cc (- amount 764 | (first-denomination kinds-of-coins)) 765 | kinds-of-coins))))) 766 | (define (first-denomination kinds-of-coins) 767 | (cond ((= kinds-of-coins 1) 1) 768 | ((= kinds-of-coins 2) 5) 769 | ((= kinds-of-coins 3) 10) 770 | ((= kinds-of-coins 4) 25) 771 | ((= kinds-of-coins 5) 50)))(count-change 100) 772 | 292 773 |

Count-change generates a tree-recursive process with redundancies similar to those in our first implementation of fib. (It will take quite a while for that 292 to be computed.) On the other hand, it is not obvious how to design a better algorithm for computing the result, and we leave this problem as a challenge. The observation that a tree-recursive process may be highly inefficient but often easy to specify and understand has led people to propose that one could get the best of both worlds by designing a "smart compiler" that could transform tree-recursive procedures into more efficient procedures that compute the same result.

One approach to coping with redundant computations is to arrange matters so that we automatically construct a table of values as they are computed. Each time we are asked to apply the procedure to some argument, we first look to see if the value is already stored in the table, in which case we avoid performing the redundant computation. This strategy, known as tabulation or memoization, can be implemented in a straightforward way. Tabulation can sometimes be used to transform processes that require an exponential number of steps (such as count-change) into processes whose space and time requirements grow linearly with the input. See exercise 3.27.

774 |

775 |
776 | 777 |

A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.

778 |
779 | 780 |

The following pattern of numbers is called Pascal's triangle.

781 | 782 | 783 |

The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it.

The elements of Pascal's triangle are called the binomial coefficients, because the nth row consists of the coefficients of the terms in the expansion of (x + y)n. This pattern for computing the coefficients appeared in Blaise Pascal's 1653 seminal work on probability theory, Traité du triangle arithmétique. According to Knuth (1973), the same pattern appears in the Szu-yuen Yü-chien ("The Precious Mirror of the Four Elements"), published by the Chinese mathematician Chu Shih-chieh in 1303, in the works of the twelfth-century Persian poet and mathematician Omar Khayyam, and in the works of the twelfth-century Hindu mathematician Bháscara Áchárya.

784 | Write a procedure that computes elements of Pascal's triangle by means of a recursive process.

785 |
786 | 787 |

Prove that Fib(n) is the closest integer to n/5, where = (1 + 5)/2. Hint: Let = (1 - 5)/2. Use induction and the definition of the Fibonacci numbers (see section 1.2.2) to prove that Fib(n) = (n - n)/5.

788 |
789 |
790 |
791 |

The previous examples illustrate that processes can differ considerably in the rates at which they consume computational resources. One convenient way to describe this difference is to use the notion of order of growth to obtain a gross measure of the resources required by a process as the inputs become larger.

792 |

Let n be a parameter that measures the size of the problem, and let R(n) be the amount of resources the process requires for a problem of size n. In our previous examples we took n to be the number for which a given function is to be computed, but there are other possibilities. For instance, if our goal is to compute an approximation to the square root of a number, we might take n to be the number of digits accuracy required. For matrix multiplication we might take n to be the number of rows in the matrices. In general there are a number of properties of the problem with respect to which it will be desirable to analyze a given process. Similarly, R(n) might measure the number of internal storage registers used, the number of elementary machine operations performed, and so on. In computers that do only a fixed number of operations at a time, the time required will be proportional to the number of elementary machine operations performed.

793 |

We say that R(n) has order of growth (f(n)), written R(n) = (f(n)) (pronounced "theta of f(n)"), if there are positive constants k1 and k2 independent of n such that

794 | 795 | 796 |

for any sufficiently large value of n. (In other words, for large n, the value R(n) is sandwiched between k1f(n) and k2f(n).)

797 |

For instance, with the linear recursive process for computing factorial described in section 1.2.1 the number of steps grows proportionally to the input n. Thus, the steps required for this process grows as (n). We also saw that the space required grows as (n). For the iterative factorial, the number of steps is still (n) but the space is (1) -- that is, constant.

These statements mask a great deal of oversimplification. For instance, if we count process steps as "machine operations" we are making the assumption that the number of machine operations needed to perform, say, a multiplication is independent of the size of the numbers to be multiplied, which is false if the numbers are sufficiently large. Similar remarks hold for the estimates of space. Like the design and description of a process, the analysis of a process can be carried out at various levels of abstraction.

798 | The tree-recursive Fibonacci computation requires (n) steps and space (n), where is the golden ratio described in section 1.2.2.

799 |

Orders of growth provide only a crude description of the behavior of a process. For example, a process requiring n2 steps and a process requiring 1000n2 steps and a process requiring 3n2 + 10n + 17 steps all have (n2) order of growth. On the other hand, order of growth provides a useful indication of how we may expect the behavior of the process to change as we change the size of the problem. For a (n) (linear) process, doubling the size will roughly double the amount of resources used. For an exponential process, each increment in problem size will multiply the resource utilization by a constant factor. In the remainder of section 1.2 we will examine two algorithms whose order of growth is logarithmic, so that doubling the problem size increases the resource requirement by a constant amount.

800 | 801 |

Draw the tree illustrating the process generated by the count-change procedure of section 1.2.2 in making change for 11 cents. What are the orders of growth of the space and number of steps used by this process as the amount to be changed increases?

802 |
803 | 804 |

The sine of an angle (specified in radians) can be computed by making use of the approximation sin x x if x is sufficiently small, and the trigonometric identity

805 | 806 | 807 |

to reduce the size of the argument of sin. (For purposes of this exercise an angle is considered "sufficiently small" if its magnitude is not greater than 0.1 radians.) These ideas are incorporated in the following procedures:

808 | (define (cube x) (* x x x)) 809 | (define (p x) (- (* 3 x) (* 4 (cube x)))) 810 | (define (sine angle) 811 | (if (not (> (abs angle) 0.1)) 812 | angle 813 | (p (sine (/ angle 3.0))))) 814 |

a. How many times is the procedure p applied when (sine 12.15) is evaluated?

815 |

b. What is the order of growth in space and number of steps (as a function of a) used by the process generated by the sine procedure when (sine a) is evaluated?

816 |
817 |
818 |
819 |

Consider the problem of computing the exponential of a given number. We would like a procedure that takes as arguments a base b and a positive integer exponent n and computes bn. One way to do this is via the recursive definition

820 | 821 | 822 |

which translates readily into the procedure

823 | (define (expt b n) 824 | (if (= n 0) 825 | 1 826 | (* b (expt b (- n 1)))))(expt 2 9)512 827 |

This is a linear recursive process, which requires (n) steps and (n) space. Just as with factorial, we can readily formulate an equivalent linear iteration:

828 | (define (expt b n) 829 | (expt-iter b n 1)) 830 | 831 | (define (expt-iter b counter product) 832 | (if (= counter 0) 833 | product 834 | (expt-iter b 835 | (- counter 1) 836 | (* b product))))(expt 2 9)512 837 |

This version requires (n) steps and (1) space.

838 |

We can compute exponentials in fewer steps by using successive squaring. For instance, rather than computing b8 as

839 | 840 | 841 |

we can compute it using three multiplications:

842 | 843 | 844 |

This method works fine for exponents that are powers of 2. We can also take advantage of successive squaring in computing exponentials in general if we use the rule

845 | 846 | 847 |

We can express this method as a procedure:

848 | (define (even? n) 849 | (= (remainder n 2) 0)) 850 | (define (square x) (* x x))(define (fast-expt b n) 851 | (cond ((= n 0) 1) 852 | ((even? n) (square (fast-expt b (/ n 2)))) 853 | (else (* b (fast-expt b (- n 1))))))(fast-expt 2 9)512 854 |

where the predicate to test whether an integer is even is defined in terms of the primitive procedure remainder by

855 | (define (even? n) 856 | (= (remainder n 2) 0))(even? 3)#f 857 |

The process evolved by fast-expt grows logarithmically with n in both space and number of steps. To see this, observe that computing b2n using fast-expt requires only one more multiplication than computing bn. The size of the exponent we can compute therefore doubles (approximately) with every new multiplication we are allowed. Thus, the number of multiplications required for an exponent of n grows about as fast as the logarithm of n to the base 2. The process has (log n) growth.

More precisely, the number of multiplications required is equal to 1 less than the log base 2 of n plus the number of ones in the binary representation of n. This total is always less than twice the log base 2 of n. The arbitrary constants k1 and k2 in the definition of order notation imply that, for a logarithmic process, the base to which logarithms are taken does not matter, so all such processes are described as (log n).

858 |

859 |

The difference between (log n) growth and (n) growth becomes striking as n becomes large. For example, fast-expt for n = 1000 requires only 14 multiplications.

You may wonder why anyone would care about raising numbers to the 1000th power. See section 1.2.6.

860 | It is also possible to use the idea of successive squaring to devise an iterative algorithm that computes exponentials with a logarithmic number of steps (see exercise 1.16), although, as is often the case with iterative algorithms, this is not written down so straightforwardly as the recursive algorithm.

This iterative algorithm is ancient. It appears in the Chandah-sutra by Áchárya Pingala, written before 200 B.C. See Knuth 1981, section 4.6.3, for a full discussion and analysis of this and other methods of exponentiation.

861 |

862 | 863 |

Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)

864 |
865 | 866 |

The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:

867 | (define (* a b) 868 | (if (= b 0) 869 | 0 870 | (+ a (* a (- b 1))))) 871 |

This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.

872 |
873 | 874 |

Using the results of exercises 1.16 and 1.17, devise a procedure that generates an iterative process for multiplying two integers in terms of adding, doubling, and halving and uses a logarithmic number of steps.

This algorithm, which is sometimes known as the "Russian peasant method" of multiplication, is ancient. Examples of its use are found in the Rhind Papyrus, one of the two oldest mathematical documents in existence, written about 1700 B.C. (and copied from an even older document) by an Egyptian scribe named A'h-mose.

875 |

876 |
877 | 878 |

There is a clever algorithm for computing the Fibonacci numbers in a logarithmic number of steps. Recall the transformation of the state variables a and b in the fib-iter process of section 1.2.2: a a + b and b a. Call this transformation T, and observe that applying T over and over again n times, starting with 1 and 0, produces the pair Fib(n + 1) and Fib(n). In other words, the Fibonacci numbers are produced by applying Tn, the nth power of the transformation T, starting with the pair (1,0). Now consider T to be the special case of p = 0 and q = 1 in a family of transformations Tpq, where Tpq transforms the pair (a,b) according to a bq + aq + ap and b bp + aq. Show that if we apply such a transformation Tpq twice, the effect is the same as using a single transformation Tp'q' of the same form, and compute p' and q' in terms of p and q. This gives us an explicit way to square these transformations, and thus we can compute Tn using successive squaring, as in the fast-expt procedure. Put this all together to complete the following procedure, which runs in a logarithmic number of steps:

This exercise was suggested to us by Joe Stoy, based on an example in Kaldewaij 1990.

879 |

880 | (define (fib n) 881 | (fib-iter 1 0 0 1 n)) 882 | (define (fib-iter a b p q count) 883 | (cond ((= count 0) b) 884 | ((even? count) 885 | (fib-iter a 886 | b 887 | <??> ; compute p' 888 | <??> ; compute q' 889 | (/ count 2))) 890 | (else (fib-iter (+ (* b q) (* a q) (* a p)) 891 | (+ (* b p) (* a q)) 892 | p 893 | q 894 | (- count 1))))) 895 |
896 |
897 |
898 |

The greatest common divisor (GCD) of two integers a and b is defined to be the largest integer that divides both a and b with no remainder. For example, the GCD of 16 and 28 is 4. In chapter 2, when we investigate how to implement rational-number arithmetic, we will need to be able to compute GCDs in order to reduce rational numbers to lowest terms. (To reduce a rational number to lowest terms, we must divide both the numerator and the denominator by their GCD. For example, 16/28 reduces to 4/7.) One way to find the GCD of two integers is to factor them and search for common factors, but there is a famous algorithm that is much more efficient.

899 |

The idea of the algorithm is based on the observation that, if r is the remainder when a is divided by b, then the common divisors of a and b are precisely the same as the common divisors of b and r. Thus, we can use the equation

900 | 901 | 902 |

to successively reduce the problem of computing a GCD to the problem of computing the GCD of smaller and smaller pairs of integers. For example,

903 | 904 | 905 |

reduces GCD(206,40) to GCD(2,0), which is 2. It is possible to show that starting with any two positive integers and performing repeated reductions will always eventually produce a pair where the second number is 0. Then the GCD is the other number in the pair. This method for computing the GCD is known as Euclid's Algorithm.

Euclid's Algorithm is so called because it appears in Euclid's Elements (Book 7, ca. 300 B.C.). According to Knuth (1973), it can be considered the oldest known nontrivial algorithm. The ancient Egyptian method of multiplication (exercise 1.18) is surely older, but, as Knuth explains, Euclid's algorithm is the oldest known to have been presented as a general algorithm, rather than as a set of illustrative examples.

906 |

907 |

It is easy to express Euclid's Algorithm as a procedure:

908 | (define (gcd a b) 909 | (if (= b 0) 910 | a 911 | (gcd b (remainder a b))))(gcd 40 30)10 912 |

This generates an iterative process, whose number of steps grows as the logarithm of the numbers involved.

913 |

The fact that the number of steps required by Euclid's Algorithm has logarithmic growth bears an interesting relation to the Fibonacci numbers:

914 |

compute the GCD of some pair, then the smaller number in the pair must be greater than or equal to the kth Fibonacci number.

This theorem was proved in 1845 by Gabriel Lamé, a French mathematician and engineer known chiefly for his contributions to mathematical physics. To prove the theorem, we consider pairs (ak ,bk), where ak> bk, for which Euclid's Algorithm terminates in k steps. The proof is based on the claim that, if (ak+1, bk+1) (ak, bk) (ak-1, bk-1) are three successive pairs in the reduction process, then we must have bk+1> bk + bk-1. To verify the claim, consider that a reduction step is defined by applying the transformation ak-1 = bk, bk-1 = remainder of ak divided by bk. The second equation means that ak = qbk + bk-1 for some positive integer q. And since q must be at least 1 we have ak = qbk + bk-1 > bk + bk-1. But in the previous reduction step we have bk+1 = ak. Therefore, bk+1 = ak> bk + bk-1. This verifies the claim. Now we can prove the theorem by induction on k, the number of steps that the algorithm requires to terminate. The result is true for k = 1, since this merely requires that b be at least as large as Fib(1) = 1. Now, assume that the result is true for all integers less than or equal to k and establish the result for k + 1. Let (ak+1, bk+1) (ak, bk) (ak-1, bk-1) be successive pairs in the reduction process. By our induction hypotheses, we have bk-1> Fib(k - 1) and bk> Fib(k). Thus, applying the claim we just proved together with the definition of the Fibonacci numbers gives bk+1 > bk + bk-1> Fib(k) + Fib(k - 1) = Fib(k + 1), which completes the proof of Lamé's Theorem.

915 |

916 |

We can use this theorem to get an order-of-growth estimate for Euclid's Algorithm. Let n be the smaller of the two inputs to the procedure. If the process takes k steps, then we must have n> Fib (k) k/5. Therefore the number of steps k grows as the logarithm (to the base ) of n. Hence, the order of growth is (log n).

917 | 918 |

The process that a procedure generates is of course dependent on the rules used by the interpreter. As an example, consider the iterative gcd procedure given above. Suppose we were to interpret this procedure using normal-order evaluation, as discussed in section 1.1.5. (The normal-order-evaluation rule for if is described in exercise 1.5.) Using the substitution method (for normal order), illustrate the process generated in evaluating (gcd 206 40) and indicate the remainder operations that are actually performed. How many remainder operations are actually performed in the normal-order evaluation of (gcd 206 40)? In the applicative-order evaluation?

919 |
920 |
921 |
922 |

This section describes two methods for checking the primality of an integer n, one with order of growth (n), and a "probabilistic" algorithm with order of growth (log n). The exercises at the end of this section suggest programming projects based on these algorithms.

923 |

Since ancient times, mathematicians have been fascinated by problems concerning prime numbers, and many people have worked on the problem of determining ways to test if numbers are prime. One way to test if a number is prime is to find the number's divisors. The following program finds the smallest integral divisor (greater than 1) of a given number n. It does this in a straightforward way, by testing n for divisibility by successive integers starting with 2.

924 | (define (square x) (* x x))(define (smallest-divisor n) 925 | (find-divisor n 2)) 926 | (define (find-divisor n test-divisor) 927 | (cond ((> (square test-divisor) n) n) 928 | ((divides? test-divisor n) test-divisor) 929 | (else (find-divisor n (+ test-divisor 1))))) 930 | (define (divides? a b) 931 | (= (remainder b a) 0))(smallest-divisor 12)2 932 |

We can test whether a number is prime as follows: n is prime if and only if n is its own smallest divisor.

933 | (define (smallest-divisor n) 934 | (find-divisor n 2)) 935 | (define (find-divisor n test-divisor) 936 | (cond ((> (square test-divisor) n) n) 937 | ((divides? test-divisor n) test-divisor) 938 | (else (find-divisor n (+ test-divisor 1))))) 939 | (define (divides? a b) 940 | (= (remainder b a) 0)) 941 | (define (square x) (* x x))(define (prime? n) 942 | (= n (smallest-divisor n)))(prime? 13)#t 943 |

The end test for find-divisor is based on the fact that if n is not prime it must have a divisor less than or equal to n.

If d is a divisor of n, then so is n/d. But d and n/d cannot both be greater than n.

944 | This means that the algorithm need only test divisors between 1 and n. Consequently, the number of steps required to identify n as prime will have order of growth (n).

945 |
946 |

The (log n) primality test is based on a result from number theory known as Fermat's Little Theorem.

Pierre de Fermat (1601-1665) is considered to be the founder of modern number theory. He obtained many important number-theoretic results, but he usually announced just the results, without providing his proofs. Fermat's Little Theorem was stated in a letter he wrote in 1640. The first published proof was given by Euler in 1736 (and an earlier, identical proof was discovered in the unpublished manuscripts of Leibniz). The most famous of Fermat's results -- known as Fermat's Last Theorem -- was jotted down in 1637 in his copy of the book Arithmetic (by the third-century Greek mathematician Diophantus) with the remark "I have discovered a truly remarkable proof, but this margin is too small to contain it." Finding a proof of Fermat's Last Theorem became one of the most famous challenges in number theory. A complete solution was finally given in 1995 by Andrew Wiles of Princeton University.

947 |

948 |

(Two numbers are said to be congruent modulo n if they both have the same remainder when divided by n. The remainder of a number a when divided by n is also referred to as the remainder of a modulo n, or simply as a modulo n.)

949 |

If n is not prime, then, in general, most of the numbers a< n will not satisfy the above relation. This leads to the following algorithm for testing primality: Given a number n, pick a random number a < n and compute the remainder of an modulo n. If the result is not equal to a, then n is certainly not prime. If it is a, then chances are good that n is prime. Now pick another random number a and test it with the same method. If it also satisfies the equation, then we can be even more confident that n is prime. By trying more and more values of a, we can increase our confidence in the result. This algorithm is known as the Fermat test.

950 |

To implement the Fermat test, we need a procedure that computes the exponential of a number modulo another number:

951 | (define (even? n) (= (remainder n 2) 0)) 952 | (define (square x) (* x x))(define (expmod base exp m) 953 | (cond ((= exp 0) 1) 954 | ((even? exp) 955 | (remainder (square (expmod base (/ exp 2) m)) 956 | m)) 957 | (else 958 | (remainder (* base (expmod base (- exp 1) m)) 959 | m))))(expmod 2 9 500)12 960 |

This is very similar to the fast-expt procedure of section 1.2.4. It uses successive squaring, so that the number of steps grows logarithmically with the exponent.

The reduction steps in the cases where the exponent e is greater than 1 are based on the fact that, for any integers x, y, and m, we can find the remainder of x times y modulo m by computing separately the remainders of x modulo m and y modulo m, multiplying these, and then taking the remainder of the result modulo m. For instance, in the case where e is even, we compute the remainder of be/2 modulo m, square this, and take the remainder modulo m. This technique is useful because it means we can perform our computation without ever having to deal with numbers much larger than m. (Compare exercise 1.25.)

961 |

962 |

The Fermat test is performed by choosing at random a number a between 1 and n - 1 inclusive and checking whether the remainder modulo n of the nth power of a is equal to a. The random number a is chosen using the procedure random, which we assume is included as a primitive in Scheme. Random returns a nonnegative integer less than its integer input. Hence, to obtain a random number between 1 and n - 1, we call random with an input of n - 1 and add 1 to the result:

963 | (define (expmod base exp m) 964 | (cond ((= exp 0) 1) 965 | ((even? exp) 966 | (remainder (square (expmod base (/ exp 2) m)) 967 | m)) 968 | (else 969 | (remainder (* base (expmod base (- exp 1) m)) 970 | m)))) 971 | (define (square x) (* x x)) 972 | (define (even? n) (= (remainder n 2) 0))(define (fermat-test n) 973 | (define (try-it a) 974 | (= (expmod a n n) a)) 975 | (try-it (+ 1 (random (- n 1)))))(fermat-test 13)#t 976 |

The following procedure runs the test a given number of times, as specified by a parameter. Its value is true if the test succeeds every time, and false otherwise.

977 | (define (expmod base exp m) 978 | (cond ((= exp 0) 1) 979 | ((even? exp) 980 | (remainder (square (expmod base (/ exp 2) m)) 981 | m)) 982 | (else 983 | (remainder (* base (expmod base (- exp 1) m)) 984 | m)))) 985 | (define (even? n) (= (remainder n 2) 0)) 986 | (define (square x) (* x x)) 987 | (define (fermat-test n) 988 | (define (try-it a) 989 | (= (expmod a n n) a)) 990 | (try-it (+ 1 (random (- n 1)))))(define (fast-prime? n times) 991 | (cond ((= times 0) true) 992 | ((fermat-test n) (fast-prime? n (- times 1))) 993 | (else false)))(fast-prime? 13 10)#t 994 |
995 |

The Fermat test differs in character from most familiar algorithms, in which one computes an answer that is guaranteed to be correct. Here, the answer obtained is only probably correct. More precisely, if n ever fails the Fermat test, we can be certain that n is not prime. But the fact that n passes the test, while an extremely strong indication, is still not a guarantee that n is prime. What we would like to say is that for any number n, if we perform the test enough times and find that n always passes the test, then the probability of error in our primality test can be made as small as we like.

996 |

Unfortunately, this assertion is not quite correct. There do exist numbers that fool the Fermat test: numbers n that are not prime and yet have the property that an is congruent to a modulo n for all integers a < n. Such numbers are extremely rare, so the Fermat test is quite reliable in practice.

Numbers that fool the Fermat test are called Carmichael numbers, and little is known about them other than that they are extremely rare. There are 255 Carmichael numbers below 100,000,000. The smallest few are 561, 1105, 1729, 2465, 2821, and 6601. In testing primality of very large numbers chosen at random, the chance of stumbling upon a value that fools the Fermat test is less than the chance that cosmic radiation will cause the computer to make an error in carrying out a "correct" algorithm. Considering an algorithm to be inadequate for the first reason but not for the second illustrates the difference between mathematics and engineering.

997 | There are variations of the Fermat test that cannot be fooled. In these tests, as with the Fermat method, one tests the primality of an integer n by choosing a random integer a<n and checking some condition that depends upon n and a. (See exercise 1.28 for an example of such a test.) On the other hand, in contrast to the Fermat test, one can prove that, for any n, the condition does not hold for most of the integers a<n unless n is prime. Thus, if n passes the test for some random choice of a, the chances are better than even that n is prime. If n passes the test for two random choices of a, the chances are better than 3 out of 4 that n is prime. By running the test with more and more randomly chosen values of a we can make the probability of error as small as we like.

998 |

The existence of tests for which one can prove that the chance of error becomes arbitrarily small has sparked interest in algorithms of this type, which have come to be known as probabilistic algorithms. There is a great deal of research activity in this area, and probabilistic algorithms have been fruitfully applied to many fields.

One of the most striking applications of probabilistic prime testing has been to the field of cryptography. Although it is now computationally infeasible to factor an arbitrary 200-digit number, the primality of such a number can be checked in a few seconds with the Fermat test. This fact forms the basis of a technique for constructing "unbreakable codes" suggested by Rivest, Shamir, and Adleman (1977). The resulting RSA algorithm has become a widely used technique for enhancing the security of electronic communications. Because of this and related developments, the study of prime numbers, once considered the epitome of a topic in "pure" mathematics to be studied only for its own sake, now turns out to have important practical applications to cryptography, electronic funds transfer, and information retrieval.

999 |

1000 |
1001 | 1002 |

Use the smallest-divisor procedure to find the smallest divisor of each of the following numbers: 199, 1999, 19999.

1003 |
1004 | 1005 |

Most Lisp implementations include a primitive called runtime that returns an integer that specifies the amount of time the system has been running (measured, for example, in microseconds). The following timed-prime-test procedure, when called with an integer n, prints n and checks to see if n is prime. If n is prime, the procedure prints three asterisks followed by the amount of time used in performing the test.

1006 | (define (timed-prime-test n) 1007 | (newline) 1008 | (display n) 1009 | (start-prime-test n (runtime))) 1010 | (define (start-prime-test n start-time) 1011 | (if (prime? n) 1012 | (report-prime (- (runtime) start-time)))) 1013 | (define (report-prime elapsed-time) 1014 | (display " *** ") 1015 | (display elapsed-time)) 1016 |

Using this procedure, write a procedure search-for-primes that checks the primality of consecutive odd integers in a specified range. Use your procedure to find the three smallest primes larger than 1000; larger than 10,000; larger than 100,000; larger than 1,000,000. Note the time needed to test each prime. Since the testing algorithm has order of growth of (n), you should expect that testing for primes around 10,000 should take about 10 times as long as testing for primes around 1000. Do your timing data bear this out? How well do the data for 100,000 and 1,000,000 support the n prediction? Is your result compatible with the notion that programs on your machine run in time proportional to the number of steps required for the computation?

1017 |
1018 | 1019 |

The smallest-divisor procedure shown at the start of this section does lots of needless testing: After it checks to see if the number is divisible by 2 there is no point in checking to see if it is divisible by any larger even numbers. This suggests that the values used for test-divisor should not be 2, 3, 4, 5, 6, ..., but rather 2, 3, 5, 7, 9, .... To implement this change, define a procedure next that returns 3 if its input is equal to 2 and otherwise returns its input plus 2. Modify the smallest-divisor procedure to use (next test-divisor) instead of (+ test-divisor 1). With timed-prime-test incorporating this modified version of smallest-divisor, run the test for each of the 12 primes found in exercise 1.22. Since this modification halves the number of test steps, you should expect it to run about twice as fast. Is this expectation confirmed? If not, what is the observed ratio of the speeds of the two algorithms, and how do you explain the fact that it is different from 2?

1020 |
1021 | 1022 |

Modify the timed-prime-test procedure of exercise 1.22 to use fast-prime? (the Fermat method), and test each of the 12 primes you found in that exercise. Since the Fermat test has (log n) growth, how would you expect the time to test primes near 1,000,000 to compare with the time needed to test primes near 1000? Do your data bear this out? Can you explain any discrepancy you find?

1023 |
1024 | 1025 |

Alyssa P. Hacker complains that we went to a lot of extra work in writing expmod. After all, she says, since we already know how to compute exponentials, we could have simply written

1026 | (define (expmod base exp m) 1027 | (remainder (fast-expt base exp) m)) 1028 |

Is she correct? Would this procedure serve as well for our fast prime tester? Explain.

1029 |
1030 | 1031 |

Louis Reasoner is having great difficulty doing exercise 1.24. His fast-prime? test seems to run more slowly than his prime? test. Louis calls his friend Eva Lu Ator over to help. When they examine Louis's code, they find that he has rewritten the expmod procedure to use an explicit multiplication, rather than calling square:

1032 | (define (expmod base exp m) 1033 | (cond ((= exp 0) 1) 1034 | ((even? exp) 1035 | (remainder (* (expmod base (/ exp 2) m) 1036 | (expmod base (/ exp 2) m)) 1037 | m)) 1038 | (else 1039 | (remainder (* base (expmod base (- exp 1) m)) 1040 | m)))) 1041 |

"I don't see what difference that could make," says Louis. "I do." says Eva. "By writing the procedure like that, you have transformed the (log n) process into a (n) process." Explain.

1042 |
1043 | 1044 |

Demonstrate that the Carmichael numbers listed in footnote 47 really do fool the Fermat test. That is, write a procedure that takes an integer n and tests whether an is congruent to a modulo n for every a<n, and try your procedure on the given Carmichael numbers.

1045 |
1046 | 1047 |

One variant of the Fermat test that cannot be fooled is called the Miller-Rabin test (Miller 1976; Rabin 1980). This starts from an alternate form of Fermat's Little Theorem, which states that if n is a prime number and a is any positive integer less than n, then a raised to the (n - 1)st power is congruent to 1 modulo n. To test the primality of a number n by the Miller-Rabin test, we pick a random number a<n and raise a to the (n - 1)st power modulo n using the expmod procedure. However, whenever we perform the squaring step in expmod, we check to see if we have discovered a "nontrivial square root of 1 modulo n," that is, a number not equal to 1 or n - 1 whose square is equal to 1 modulo n. It is possible to prove that if such a nontrivial square root of 1 exists, then n is not prime. It is also possible to prove that if n is an odd number that is not prime, then, for at least half the numbers a<n, computing an-1 in this way will reveal a nontrivial square root of 1 modulo n. (This is why the Miller-Rabin test cannot be fooled.) Modify the expmod procedure to signal if it discovers a nontrivial square root of 1, and use this to implement the Miller-Rabin test with a procedure analogous to fermat-test. Check your procedure by testing various known primes and non-primes. Hint: One convenient way to make expmod signal is to have it return 0.

1048 |
1049 | 1050 |
1051 |
1052 | 1053 |
1054 | 1055 | 1056 | 1057 |
1058 |

Learn Scheme is an adaptation of Structure and Interpretation of Computer Programs by Harold Abelson and Gerald Jay Sussman with Julie Sussman, second edition, published by the MIT Press.

1059 |

The content has been reformatted for the Web and made interactive by Jared Krinke. The Scheme interpreter is (c) 2015 Jared Krinke.

1060 |
1061 |

Educators, generals, dieticians, psychologists, and parents program. Armies, students, and some societies are programmed. An assault on large problems employs a succession of programs, most of which spring into existence en route. These programs are rife with issues that appear to be particular to the problem at hand. To appreciate programming as an intellectual activity in its own right you must turn to computer programming; you must read and write computer programs -- many of them. It doesn't matter much what the programs are about or what applications they serve. What does matter is how well they perform and how smoothly they fit with other programs in the creation of still greater programs. The programmer must seek both perfection of part and adequacy of collection. In this book the use of "program" is focused on the creation, execution, and study of programs written in a dialect of Lisp for execution on a digital computer. Using Lisp we restrict or limit not what we may program, but only the notation for our program descriptions.

1062 |

Our traffic with the subject matter of this book involves us with three foci of phenomena: the human mind, collections of computer programs, and the computer. Every computer program is a model, hatched in the mind, of a real or mental process. These processes, arising from human experience and thought, are huge in number, intricate in detail, and at any time only partially understood. They are modeled to our permanent satisfaction rarely by our computer programs. Thus even though our programs are carefully handcrafted discrete collections of symbols, mosaics of interlocking functions, they continually evolve: we change them as our perception of the model deepens, enlarges, generalizes until the model ultimately attains a metastable place within still another model with which we struggle. The source of the exhilaration associated with computer programming is the continual unfolding within the mind and on the computer of mechanisms expressed as programs and the explosion of perception they generate. If art interprets our dreams, the computer executes them in the guise of programs!

1063 |

For all its power, the computer is a harsh taskmaster. Its programs must be correct, and what we wish to say must be said accurately in every detail. As in every other symbolic activity, we become convinced of program truth through argument. Lisp itself can be assigned a semantics (another model, by the way), and if a program's function can be specified, say, in the predicate calculus, the proof methods of logic can be used to make an acceptable correctness argument. Unfortunately, as programs get large and complicated, as they almost always do, the adequacy, consistency, and correctness of the specifications themselves become open to doubt, so that complete formal arguments of correctness seldom accompany large programs. Since large programs grow from small ones, it is crucial that we develop an arsenal of standard program structures of whose correctness we have become sure -- we call them idioms -- and learn to combine them into larger structures using organizational techniques of proven value. These techniques are treated at length in this book, and understanding them is essential to participation in the Promethean enterprise called programming. More than anything else, the uncovering and mastery of powerful organizational techniques accelerates our ability to create large, significant programs. Conversely, since writing large programs is very taxing, we are stimulated to invent new methods of reducing the mass of function and detail to be fitted into large programs.

1064 |

Unlike programs, computers must obey the laws of physics. If they wish to perform rapidly -- a few nanoseconds per state change -- they must transmit electrons only small distances (at most 1 1/2 feet). The heat generated by the huge number of devices so concentrated in space has to be removed. An exquisite engineering art has been developed balancing between multiplicity of function and density of devices. In any event, hardware always operates at a level more primitive than that at which we care to program. The processes that transform our Lisp programs to "machine" programs are themselves abstract models which we program. Their study and creation give a great deal of insight into the organizational programs associated with programming arbitrary models. Of course the computer itself can be so modeled. Think of it: the behavior of the smallest physical switching element is modeled by quantum mechanics described by differential equations whose detailed behavior is captured by numerical approximations represented in computer programs executing on computers composed of ...!

1065 |

It is not merely a matter of tactical convenience to separately identify the three foci. Even though, as they say, it's all in the head, this logical separation induces an acceleration of symbolic traffic between these foci whose richness, vitality, and potential is exceeded in human experience only by the evolution of life itself. At best, relationships between the foci are metastable. The computers are never large enough or fast enough. Each breakthrough in hardware technology leads to more massive programming enterprises, new organizational principles, and an enrichment of abstract models. Every reader should ask himself periodically "Toward what end, toward what end?" -- but do not ask it too often lest you pass up the fun of programming for the constipation of bittersweet philosophy.

1066 |

Among the programs we write, some (but never enough) perform a precise mathematical function such as sorting or finding the maximum of a sequence of numbers, determining primality, or finding the square root. We call such programs algorithms, and a great deal is known of their optimal behavior, particularly with respect to the two important parameters of execution time and data storage requirements. A programmer should acquire good algorithms and idioms. Even though some programs resist precise specifications, it is the responsibility of the programmer to estimate, and always to attempt to improve, their performance.

1067 |

Lisp is a survivor, having been in use for about a quarter of a century. Among the active programming languages only Fortran has had a longer life. Both languages have supported the programming needs of important areas of application, Fortran for scientific and engineering computation and Lisp for artificial intelligence. These two areas continue to be important, and their programmers are so devoted to these two languages that Lisp and Fortran may well continue in active use for at least another quarter-century.

1068 |

Lisp changes. The Scheme dialect used in this text has evolved from the original Lisp and differs from the latter in several important ways, including static scoping for variable binding and permitting functions to yield functions as values. In its semantic structure Scheme is as closely akin to Algol 60 as to early Lisps. Algol 60, never to be an active language again, lives on in the genes of Scheme and Pascal. It would be difficult to find two languages that are the communicating coin of two more different cultures than those gathered around these two languages. Pascal is for building pyramids -- imposing, breathtaking, static structures built by armies pushing heavy blocks into place. Lisp is for building organisms -- imposing, breathtaking, dynamic structures built by squads fitting fluctuating myriads of simpler organisms into place. The organizing principles used are the same in both cases, except for one extraordinarily important difference: The discretionary exportable functionality entrusted to the individual Lisp programmer is more than an order of magnitude greater than that to be found within Pascal enterprises. Lisp programs inflate libraries with functions whose utility transcends the application that produced them. The list, Lisp's native data structure, is largely responsible for such growth of utility. The simple structure and natural applicability of lists are reflected in functions that are amazingly nonidiosyncratic. In Pascal the plethora of declarable data structures induces a specialization within functions that inhibits and penalizes casual cooperation. It is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures. As a result the pyramid must stand unchanged for a millennium; the organism must evolve or perish.

1069 |

To illustrate this difference, compare the treatment of material and exercises within this book with that in any first-course text using Pascal. Do not labor under the illusion that this is a text digestible at MIT only, peculiar to the breed found there. It is precisely what a serious book on programming Lisp must be, no matter who the student is or where it is used.

1070 |

Note that this is a text about programming, unlike most Lisp books, which are used as a preparation for work in artificial intelligence. After all, the critical programming concerns of software engineering and artificial intelligence tend to coalesce as the systems under investigation become larger. This explains why there is such growing interest in Lisp outside of artificial intelligence.

1071 |

As one would expect from its goals, artificial intelligence research generates many significant programming problems. In other programming cultures this spate of problems spawns new languages. Indeed, in any very large programming task a useful organizing principle is to control and isolate traffic within the task modules via the invention of language. These languages tend to become less primitive as one approaches the boundaries of the system where we humans interact most often. As a result, such systems contain complex language-processing functions replicated many times. Lisp has such a simple syntax and semantics that parsing can be treated as an elementary task. Thus parsing technology plays almost no role in Lisp programs, and the construction of language processors is rarely an impediment to the rate of growth and change of large Lisp systems. Finally, it is this very simplicity of syntax and semantics that is responsible for the burden and freedom borne by all Lisp programmers. No Lisp program of any size beyond a few lines can be written without being saturated with discretionary functions. Invent and fit; have fits and reinvent! We toast the Lisp programmer who pens his thoughts within nests of parentheses.

1072 | 1073 |
1074 |
1075 | 1076 |
1077 |

Learn Scheme is an adaptation of Structure and Interpretation of Computer Programs by Harold Abelson and Gerald Jay Sussman with Julie Sussman, second edition, published by the MIT Press. (c) 1996 by Massachusetts Institute of Technology.

1078 |

The content has been reformatted for the Web and made interactive by Jared Krinke. The Scheme interpreter is (c) 2015 Jared Krinke.

1079 |

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

1080 |
1081 |
1082 | 1083 |
1084 | -------------------------------------------------------------------------------- /html.xsl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | <xsl:value-of select="concat($brand, ' - ', $title)"/> 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 |
35 | 36 | 61 | 62 | 63 | 64 | 75 | 76 | 77 |
78 | 79 | 101 | 102 | 103 | 104 |
105 |
106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 |

116 | 117 |
118 |
119 |
120 | 121 | 122 | 123 |

124 | 125 | 126 |

127 | 128 |
129 |
130 | 131 | 132 | 133 |
134 | 135 |
136 |
137 | 138 | 139 | Exercise 140 | 141 | 142 | 143 | 144 |

145 | 146 |
147 |
148 | 149 | 150 | 151 | Figure : 152 | 153 | 154 |

155 |
156 | 157 | 158 |
159 |
160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 |
  • 266 | 267 |
  • 268 | 269 |
      270 | 271 | 272 | 273 |
    274 |
    275 |
    276 | 277 | 278 | 279 | 280 | 281 | 282 |
      283 | 284 | 285 | 286 |
    287 |
    288 |
    289 |
    290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 |
    309 | 310 | 311 | 312 |
    313 |
    314 |
    315 | 316 | 317 |

    318 | 319 |
    320 | 321 |

    322 |
    323 | 324 |
    325 | 326 |
    327 |
    328 |
    329 | 330 | 331 | 332 | 333 | 334 | code-invalid 335 | 336 | 337 | 338 | 339 | 340 |
    341 |
    342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 |
    376 | -------------------------------------------------------------------------------- /tests.xsl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | --------------------------------------------------------------------------------