{{title}}
<title>iSICP 1.1 - The Elements of Programming</title>
@@

{{main_text}}
<a href='index.html' style="float:left"> <img src='images/chevron-up.svg' height=64 width=64> </a>
<span style="float:right">
<a href='1-0-abstractions.html'> <img src='images/chevron-left.svg' height=64 width=64> </a>
<a href='1-2-procedures.html'> <img src='images/chevron-right.svg' height=64 width=64> </a>
</span>
<br> <br>
<h2> The Elements of Programming </h2>

<hr>

<p> 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:

<ul>

<li> <p> <b> primitive expressions, </b> which represent the simplest entities the language is concerned with,

<li> <p> <b> means of combination, </b> by which compound elements are built from simpler ones, and

<li> <p> <b> means of abstraction, </b> by which compound elements can be named and manipulated as units.

</ul>

<p> 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 &ldquo;stuff&thinsp;&rdquo; 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.

<p> In this chapter we will deal only with simple numerical data so that we can focus on the rules for building procedures.<a name="footnote_link_1-4" class="footnote_link" href="#footnote_1-4">4</a> In later chapters we will see that these same rules allow us to build procedures to manipulate compound data as well.

<a name="%_sec_1.1.1" />
<h3> 1.1.1 Expressions </h3>

<p> 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.

<p> 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

<div id="scheme-number">
486
</div>
<script>
C.make_editable("scheme-number");
</script>

<p> the interpreter will respond by printing<a name="footnote_link_1-5" class="footnote_link" href="#footnote_1-5">5</a>

<div id="scheme-number-output" class="output"> </div>
<script>
C.editor_of["scheme-number"].setOption('onBlur', function() {
  return C.compute("scheme-number");
});
</script>

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

<div id="scheme-plus-1">
(+ 137 349)
</div>
<script> C.prompt("scheme-plus-1"); </script>

<p>

<div id="scheme-minus">
(- 1000 334)
</div>
<script> C.prompt("scheme-minus"); </script>

<p>

<div id="scheme-times">
(* 5 99)
</div>
<script> C.prompt("scheme-times"); </script>

<p>

<div id="scheme-divide">
(/ 10 5)
</div>
<script> C.prompt("scheme-divide"); </script>

<p>

<div id="scheme-plus-float">
(+ 2.7 10)
</div>
<script> C.prompt("scheme-plus-float"); </script>

<p> 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.

<p> 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:

<div id="scheme-plus-multiple">
(+ 21 35 12 7)
</div>
<script>
C.prompt("scheme-plus-multiple");
</script>

<p>

<div id="scheme-times-multiple">
(* 25 4 12)
</div>
<script>
C.prompt("scheme-times-multiple");
</script>

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

<p> 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:

<div id="scheme-plus-times">
(+ (* 3 5) (- 10 6))
</div>
<script>
C.prompt("scheme-plus-times");
</script>

<p> 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

<div id="scheme-long-tree">
(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))
</div>
<script>
C.prompt("scheme-long-tree");
</script>

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

<div id="scheme-long-tree-pp">
(+ (* 3
      (+ (* 2 4)
         (+ 3 5)))
   (+ (- 10 7)
      6))
</div>
<script>
C.prompt("scheme-long-tree-pp");
</script>

<p> 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.<a name="footnote_link_1-6" class="footnote_link" href="#footnote_1-6">6</a>

<p> 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.<a name="footnote_link_1-7" class="footnote_link" href="#footnote_1-7">7</a>

<div class='exercise'>

<p> <b> Exercise 1.1.1. </b>  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.

<div id="scheme-ex-111-10" class='static'>
10
</div>
<script>
C.answer("scheme-ex-111-10", 10);
</script>

<p>

<div id="scheme-ex-111-plus" class='static'>
(+ 5 3 4)
</div>
<script>
C.answer("scheme-ex-111-plus", 12);
</script>

<p>

<div id="scheme-ex-111-minus" class='static'>
(- 9 1)
</div>
<script>
C.answer("scheme-ex-111-minus", 8);
</script>

<p>

<div id="scheme-ex-111-div" class='static'>
(/ 6 2)
</div>
<script>
C.answer("scheme-ex-111-div", 3);
</script>

<p>

<div id="scheme-ex-111-nested" class='static'>
(+ (* 2 4) (- 4 6))
</div>
<script>
C.answer("scheme-ex-111-nested", 6);
</script>
</div>

<p>

<div class='exercise'>

<p> <b> Exercise 1.2. </b>  Translate the following expression into prefix form.

$$
\frac{5 + 4 + (2 - (3 - (6 + \frac{4}{5})))}{3(6-2)(2-7)}
$$

<div id="scheme-ex-12-input" class='input'></div>

<script>
C.make_prompting_input("scheme-ex-12-input");
C.add_output("scheme-ex-12-input");
var editor = C.editor_of["scheme-ex-12-input"];
editor.setOption('onBlur', function() {
  var code = "(equal? (quote " + editor.getValue() + ") " +
      "'(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7))))";

  C.eval_scheme(code).then(function(res){
    if (res[res.length - 1] === "true") {
      C.$_("scheme-ex-12-input-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
    } else {
      C.$_("scheme-ex-12-input-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
    }
  })
});

/*
(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7)))
*/

</script>
</div>

<a name="%_sec_1.1.2" />
<h3> 1.1.2 Naming and the Environment </h3>

<p> 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.

<p> In the Scheme dialect of Lisp, we name things with <tt>define</tt>. Typing

<div id="scheme-define-size">
(define size 2)
</div>
<script>
C.prompt("scheme-define-size");
</script>

<p> causes the interpreter to associate the value <tt>2</tt> with the name <tt>size</tt>.<a name="footnote_link_1-8" class="footnote_link" href="#footnote_1-8">8</a> Once the name <tt>size</tt> has been associated with the number <tt>2</tt>, we can refer to the value <tt>2</tt> by name:

<div id="scheme-size">
size
</div>
<script>
C.prompt("scheme-size", ["scheme-define-size"]);
</script>

<p>

<div id="scheme-times-size">
(* 5 size)
</div>
<script>
C.prompt("scheme-times-size", ["scheme-define-size"]);
</script>

<p> Here are further examples of the use of <tt>define</tt>:

<div id="scheme-define-radius">
(define pi 3.14159)
(define radius 10)
</div>
<script>
C.prompt("scheme-define-radius");
</script>

<div id="scheme-pi-r-squared">
(* pi (* radius radius))
</div>
<script>
C.prompt("scheme-pi-r-squared", ["scheme-define-radius"]);
</script>

<p>

<div id="scheme-define-circumference">
(define circumference (* 2 pi radius))
</div>
<script>
C.prompt("scheme-define-circumference", ["scheme-define-radius"]);
</script>

<div id="scheme-circumference">
circumference
</div>
<script>
C.prompt("scheme-circumference", ["scheme-define-circumference"]);
</script>

<p> <tt>define</tt> 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.

<p> 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).<a name="footnote_link_1-9" class="footnote_link" href="#footnote_1-9">9</a>

<div class='exercise'>

<p> <b> Exercise 1.1.2. </b>  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.

<div id="scheme-ex-112-define-a" class='static'>
(define a 3)
</div>
<script>
C.make_static("scheme-ex-112-define-a");
</script>

<p>

<div id="scheme-ex-112-define-b" class='static'>
(define b (+ a 1))
</div>
<script>
C.make_static("scheme-ex-112-define-b");
</script>

<p>

<div id="scheme-ex-112-plus" class='static'>
(+ a b (* a b))
</div>
<script>
C.answer("scheme-ex-112-plus", 19);
</script>

<p>

<div id="scheme-ex-112-eq" class='static'>
(= a b)
</div>
<script>
C.answer("scheme-ex-112-eq", "false");
</script>



</div>

<a name="%_sec_1.1.3" />
<h3> 1.1.3 Evaluating Combinations </h3>

<p> 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.

<blockquote> To evaluate a combination, do the following:

<ol>

<li> Evaluate the subexpressions of the combination.
<p>
<li> 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). </ol> </blockquote>

<p> 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.<a name="footnote_link_1-10" class="footnote_link" href="#footnote_1-10">10</a>

<p> 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

<div id="scheme-tree-eg">
(* (+ 2 (* 4 6))
   (+ 3 5 7))
</div>
<div id="gout"> </div>
<script>

function tokenize(sexp) {
  return eval(sexp.replace(/\n/g, " ")
                  .replace(/\(/g, "[")
                  .replace(/\)/g, "]")
                  .replace(/\*+/g,"'*'") //stupid gedit doesn't
                  .replace(/\/+/g,"'/'") //recognise regexps
                  .replace(/\+/g, "'+'")
                  .replace(/\-/g, "'-'")
                  .replace(/\s+/g,","));
}

function process(array) {
  var counter = 0;
  function iter(e) {
    if ($.isArray(e)) {
      var ret = e.map(iter);
      ret.id = counter++;
      return ret;
    } else {
      return String(e) + "id" + counter++;
    }
  }
  return iter(array);
}

function id(e) {
  if ($.isArray(e)) {
    return e.id;
  } else {
    return e.split('id')[1];
  }
}

function evaluate_a(a) {

  console.log(a);

  return ""; //TODO

  if ($.isArray(a)) {
    var op = a[0].split('id')[0];

    if (op == '+') {
      return;
    }

  }
}

function dot(a) {
  var s = "";

  if ($.isArray(a)) {

    s = s + id(a) + ' [label="' + evaluate_a(a) +'"];\n';

    for (var i = 0; i < a.length; i++) {
      s = s + dot(a[i]);
      s = s + id(a) + '->' + id(a[i]) + ';\n';
    }
  } else {
    s = s + id(a) + ' [label="' + a.split('id')[0] + '"];\n';
  }

  return s;
}

var tripped = false;
C.make_editable("scheme-tree-eg");
C.add_output("scheme-tree-eg");
C.link_editor("scheme-tree-eg", "scheme-tree-eg-output", function(x, y) {
  if (tripped) {
    var dout = dot(process(tokenize(y)));
    function update() {
      var svg = Viz('digraph {' + dout + '}', "svg");
      $("#gv-out").html(svg);
    }
    if (typeof Viz == "undefined") {
      $("#gv-out").html("<p style='text-align:center'>loading <tt>mdaines/viz.js</tt>")
      $.getScript('http://mdaines.github.com/viz.js/viz.js', update);
    } else {
      update();
    }
  } else {
    tripped = true;
  }

  C.eval_editor(x).then(function(res){
    C.$_("scheme-tree-eg-output").empty().append(res);
  })
  return "";
});
</script>

<p> 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.

<p> <div id='gv-out'> <img class='center' src="images/ch1-Z-G-1.gif"> </img> <br> </div>
<p style="text-align:center"> <b> Figure 1.1 </b>:  Tree representation, showing the value of each subcombination.

<p> 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.

<p> 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

<ul>
<li> the values of numerals are the numbers that they name,
<p>
<li> the values of built-in operators are the machine instruction sequences that carry out the corresponding operations, and
<p>
<li> the values of other names are the objects associated with those names in the environment.
</ul>

<p> 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 <tt>(+ x 1)</tt> without specifying any information about the environment that would provide a meaning for the symbol <tt>x</tt> (or even for the symbol <tt>+</tt>). 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.

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

<p> 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.<a name="footnote_link_1-11" class="footnote_link" href="#footnote_1-11">11</a>

<a name="%_sec_1.1.4" />
<h3> 1.1.4 Compound Procedures </h3>

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

<ul>
<li> Numbers and arithmetic operations are primitive data and procedures.
<p>
<li> Nesting of combinations provides a means of combining operations.
<p>
<li> Definitions that associate names with values provide a limited means of abstraction.
</ul>

<p> 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.

<p> 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

<div id="scheme-define-square">
(define (square x) (* x x))
</div>
<script>
C.prompt("scheme-define-square");
</script>

<p> We can understand this in the following way:

<p><p>
<pre>
(define&nbsp;(square&nbsp;&nbsp;x)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x))
&nbsp;&nbsp;&#8593;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8593;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8593;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8593;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8593;&nbsp;&nbsp;&nbsp;&nbsp;&#8593;
&nbsp;To&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;square&nbsp;something,&nbsp;multiply&nbsp;&nbsp;&nbsp;it&nbsp;by&nbsp;&nbsp;itself.<br>
</pre>

<p> 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.<a name="footnote_link_1-12" class="footnote_link" href="#footnote_1-12">12</a>

<p> The general form of a procedure definition is

<div id="scheme-define-syntax" class='static'>
(define (&lt;<em>name</em>&gt; &lt;<em>formal parameters</em>&gt;) &lt;<em>body</em>&gt;)
</div>
<script>
C.make_static("scheme-define-syntax");
</script>

<p> The &lt;<em>name</em>&gt; is a symbol to be associated with the procedure definition in the environment.<a name="footnote_link_1-13" class="footnote_link" href="#footnote_1-13">13</a> The &lt;<em>formal parameters</em>&gt; are the names used within the body of the procedure to refer to the corresponding arguments of the procedure. The &lt;<em>body</em>&gt; 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.<a name="footnote_link_1-14" class="footnote_link" href="#footnote_1-14">14</a> The &lt;<em>name</em>&gt; and the &lt;<em>formal parameters</em>&gt; are grouped within parentheses, just as they would be in an actual call to the procedure being defined.

<p> Having defined square, we can now use it:

<div id="scheme-square-number">
(square 21)
</div>
<script>
C.prompt("scheme-square-number", ["scheme-define-square"]);
</script>

<p>

<div id="scheme-square-sum">
(square (+ 2 5))
</div>
<script>
C.prompt("scheme-square-sum", ["scheme-define-square"]);
</script>

<p>

<div id="scheme-square-square">
(square (square 3))
</div>
<script>
C.prompt("scheme-square-square", ["scheme-define-square"]);
</script>


<p> We can also use square as a building block in defining other procedures. For example, $x^2 + y^2$ can be expressed as

<div id="scheme-sum-square-eg" class='static'>
(+ (square x) (square y))
</div>
<script>
C.make_static("scheme-sum-square-eg");
</script>

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

<div id="scheme-define-sum-of-squares">
(define (sum-of-squares x y)
  (+ (square x) (square y)))
</div>
<script>
C.prompt("scheme-define-sum-of-squares", ["scheme-define-square"]);
</script>

<div id="scheme-sum-of-squares-3-4">
(sum-of-squares 3 4)
</div>
<script>
C.prompt("scheme-sum-of-squares-3-4", ["scheme-define-sum-of-squares"]);
</script>

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

<div id="scheme-f">
(define (f a)
  (sum-of-squares (+ a 1) (* a 2)))

(f 5)
</div>
<script>
C.prompt("scheme-f", ["scheme-define-sum-of-squares"]);
</script>

<p> 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 <tt>+</tt> and <tt>*</tt>, or defined as a compound procedure.

<a name="%_sec_1.1.5" />
<h3> 1.1.5 The Substitution Model for Procedure Application</h3>

<p> 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 <a href="1-1-elements.html#%_sec_1.1.3">1.1.3</a>. 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).

<p> 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:

<blockquote> <p> To apply a compound procedure to arguments, evaluate the body of the procedure with each formal parameter replaced by the corresponding argument. </blockquote>

<p> To illustrate this process, let's evaluate the combination

<div id="scheme-f-1" class='static'>
(f 5)
</div>
<script>
C.make_static("scheme-f-1");
</script>

<p> where <tt>f</tt> is the procedure defined in section <a href="1-1-elements.html#%_sec_1.1.4">1.1.4</a>. We begin by retrieving the body of <tt>f</tt>:

<div id="scheme-f-2" class='static'>
(sum-of-squares (+ a 1) (* a 2))
</div>
<script>
C.make_static("scheme-f-2");
</script>

<p> Then we replace the formal parameter <tt>a</tt> by the argument <tt>5</tt>:

<div id="scheme-f-3" class='static'>
(sum-of-squares (+ 5 1) (* 5 2))
</div>
<script>
C.make_static("scheme-f-3");
</script>

<p> Thus the problem reduces to the evaluation of a combination with two operands and an operator <tt>sum-of-squares</tt>. 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 <tt>(+ 5 1)</tt> produces <tt>6</tt> and <tt>(* 5 2)</tt> produces <tt>10</tt>, 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

<div id="scheme-f-4" class='static'>
(+ (square 6) (square 10))
</div>
<script>
C.make_static("scheme-f-4");
</script>

<p> If we use the definition of square, this reduces to

<div id="scheme-f-5" class='static'>
(+ (* 6 6) (* 10 10))
</div>
<script>
C.make_static("scheme-f-5");
</script>

<p> which reduces by multiplication to

<div id="scheme-f-6" class='static'>
(+ 36 100)
</div>
<script>
C.make_static("scheme-f-6");
</script>

<p> and finally to

<div id="scheme-f-7" class='static'>
136
</div>
<script>
C.make_static("scheme-f-7");
</script>

<p> 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:

<ul>

<li>
<p> 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.
</li>

<li> <p> 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 &mdash; 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.<a name="footnote_link_1-15" class="footnote_link" href="#footnote_1-15">15</a>
</li>
</ul>

<h4> Applicative order versus normal order </h4>

<p> According to the description of evaluation given in section <a href="1-1-elements.html#%_sec_1.1.3">1.1.3</a>, 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

<div id="scheme-f-1-n" class='static'>
(f 5)
</div>
<script>
C.make_static("scheme-f-1-n");
</script>

<p> would proceed according to the sequence of expansions

<div id="scheme-f-2-n" class='static'>
(sum-of-squares (+ 5 1) (* 5 2))
</div>
<script>
C.make_static("scheme-f-2-n");
</script>

<p>

<div id="scheme-f-3-n" class='static'>
(+    (square (+ 5 1))      (square (* 5 2))  )
</div>
<script>
C.make_static("scheme-f-3-n");
</script>

<p>

<div id="scheme-f-4-n" class='static'>
(+    (* (+ 5 1) (+ 5 1))   (* (* 5 2) (* 5 2)))
</div>
<script>
C.make_static("scheme-f-4-n");
</script>

<p> followed by the reductions

<div id="scheme-f-5-n" class='static'>
(+         (* 6 6)             (* 10 10))
</div>
<script>
C.make_static("scheme-f-5-n");
</script>

<p>

<div id="scheme-f-6-n" class='static'>
(+           36                   100)
</div>
<script>
C.make_static("scheme-f-6-n");
</script>

<p>

<div id="scheme-f-7-n" class='static'>
                    136
</div>
<script>
C.make_static("scheme-f-7-n");
</script>

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

<div id="scheme-x" class='static'>
(* x x)
</div>
<script>
C.make_static("scheme-x");
</script>

<p> with <tt>x</tt> replaced respectively by <tt>(+ 5 1)</tt> and <tt>(* 5 2)</tt>.

<p> 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.)

<p> Lisp uses applicative-order evaluation, partly because of the additional efficiency obtained from avoiding multiple evaluations of expressions such as those illustrated with <tt>(+ 5 1)</tt> and <tt>(* 5 2)</tt> 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.<a name="footnote_link_1-16" class="footnote_link" href="#footnote_1-16">16</a>

<a name="%_sec_1.1.6" />
<h3> 1.1.6 Conditional Expressions and Predicates</h3>

<p> 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

$$
|x| = \begin{cases}
x  &amp;\mbox{if } x &gt; 0 \\
0  &amp;\mbox{if } x =    0 \\
-x &amp;\mbox{if } x &lt; 0 \end{cases}
$$

<p> 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:

<div id="scheme-cond">
(define (abs x)
  (cond ((> x 0) x)
        ((= x 0) 0)
        ((&lt; x 0) (- x))))
</div>
<script> C.prompt("scheme-cond"); </script>

<p> The general form of a conditional expression is

<div id="scheme-cond-syntax">
(cond (&lt;p1&gt; &lt;e1&gt;)
      (&lt;p2&gt; &lt;e2&gt;)
      ...
      (&lt;pn&gt; &lt;en&gt;))

</div>
<script>
C.no_output_frozen_prompt("scheme-cond-syntax");
</script>

<p> consisting of the symbol cond followed by parenthesized pairs of expressions <tt>(&lt;p&gt; &lt;e&gt;)</tt> called clauses. The first expression in each pair is a predicate &mdash; that is, an expression whose value is interpreted as either true or false.<a name="footnote_link_1-17" class="footnote_link" href="#footnote_1-17">17</a>

<p> Conditional expressions are evaluated as follows. The predicate <tt>&lt;p1&gt;</tt> is evaluated first. If its value is false, then <tt>&lt;p2&gt;</tt> is evaluated. If <tt>&lt;p2&gt;</tt>'s value is also false, then <tt>&lt;p3&gt;</tt> 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 <tt>&lt;e&gt;</tt> of the clause as the value of the conditional expression. If none of the <tt>&lt;p&gt;</tt>'s is found to be true, the value of the cond is undefined.

<p> 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 <tt>&gt;</tt>, <tt>&lt;</tt>, and <tt>=</tt>.<a name="footnote_link_1-18" class="footnote_link" href="#footnote_1-18">18</a> 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.

<p> Another way to write the absolute-value procedure is

<div id="scheme-abs">
(define (abs x)
  (cond ((&lt; x 0) (- x))
        (else x)))
</div>
<script> C.prompt("scheme-abs"); </script>

<p> which could be expressed in English as "If $x$ is less than zero return $-x$; otherwise return $x$." <tt>else</tt> is a special symbol that can be used in place of the <tt>&lt;p&gt;</tt> in the final clause of a cond. This causes the cond to return as its value the value of the corresponding <tt>&lt;e&gt;</tt> whenever all previous clauses have been bypassed. In fact, any expression that always evaluates to a true value could be used as the <tt>&lt;p&gt;</tt> here.
<p> Here is yet another way to write the absolute-value procedure:

<div id="scheme-abs-if">
(define (abs x)
  (if (&lt; x 0)
      (- x)
      x))
</div>
<div id="scheme-abs-output" class="output"> </div>
<script> C.prompt("scheme-abs-if"); </script>

<p> 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

<div id="scheme-if-syntax" class='static'>
(if &lt;predicate&gt; &lt;consequent&gt; &lt;alternative&gt;)
</div>
<script> C.no_output_frozen_prompt("scheme-if-syntax"); </script>

<p> To evaluate an if expression, the interpreter starts by evaluating the <tt>&lt;predicate&gt;</tt> part of the expression. If the <tt>&lt;predicate&gt;</tt> evaluates to a true value, the interpreter then evaluates the <tt>&lt;consequent&gt;</tt> and returns its value. Otherwise it evaluates the <tt>&lt;alternative&gt;</tt> and returns its value.<a name="footnote_link_1-19" class="footnote_link" href="#footnote_1-19">19</a>

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

<ul>

<li>

<tt>(and &lt;e1&gt; ... &lt;en&gt;)</tt>

<p> The interpreter evaluates the expressions <tt>&lt;e&gt;</tt> one at a time, in left-to-right order. If any <tt>&lt;e&gt;</tt> evaluates to false, the value of the and expression is false, and the rest of the <tt>&lt;e&gt;</tt>'s are not evaluated. If all <tt>&lt;e&gt;</tt>'s evaluate to true values, the value of the and expression is the value of the last one.

<li>

<tt>(or &lt;e1&gt; ... &lt;en&gt;)</tt>

<p> The interpreter evaluates the expressions <tt>&lt;e&gt;</tt> one at a time, in left-to-right order. If any <tt>&lt;e&gt;</tt> evaluates to a true value, that value is returned as the value of the or expression, and the rest of the <tt>&lt;e&gt;</tt>'s are not evaluated. If all <tt>&lt;e&gt;</tt>'s evaluate to false, the value of the or expression is false.

<li>

<tt>(not &lt;e&gt;)</tt>

<p> The value of a not expression is true when the expression <tt>&lt;e&gt;</tt> evaluates to false, and false otherwise.

</ul>

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

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

<div id="scheme-between">
(and (> x 5) (&lt; x 10))
</div>
<script> C.no_output_frozen_prompt("scheme-between"); </script>

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

<div id="scheme-le">
(define (>= x y)
  (or (> x y) (= x y)))
</div>
<script> C.prompt("scheme-le"); </script>

<p> or alternatively as

<div id="scheme-le-2">
(define (&gt;= x y)
  (not (&lt; x y)))
</div>
<script> C.prompt("scheme-le-2"); </script>

<p>

<div class='exercise'>

<p> <b> Exercise 1.3. </b> Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

<div id="scheme-ex-define-square-sum-larger" class='input'>
(define (square-sum-larger a b c)
  'your-code-here 42)
</div>

<script>
C.make_editable("scheme-ex-define-square-sum-larger");
C.add_output("scheme-ex-define-square-sum-larger");
C.editor_of["scheme-ex-define-square-sum-larger"].setOption("onBlur", function(){

  function ssl(a, b, c) {
    if (c > b) return ssl(a, c, b);
    if (c > a) return ssl(c, b, a);
    return (a*a) + (b*b);
  }


  function ssls(a, b, c) {
    return "(= (square-sum-larger {0} {1} {2}) {3})".format(a,b,c,ssl(a,b,c));
  }


  var code = "{0} \n (and {1} {2} {3} {4})".format(C.editor_of["scheme-ex-define-square-sum-larger"].getValue(),
                                                   ssls(1, 2, 3),
                                                   ssls(12, 2, 7),
                                                   ssls(4, 13, 6),
                                                   ssls(2, 13, 5));;

  C.eval_scheme(code).then(function(res){
    if (res[res.length - 1] === "true") {
      C.$_("scheme-ex-define-square-sum-larger-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
    } else {
      C.$_("scheme-ex-define-square-sum-larger-output").empty().append($("<div class='wrong-answer'> \u2717 </div>")).append(res);
    }
  });
});

/*
(define (square-sum-larger a b c)
  (cond ((> c b) (square-sum-larger a c b))
        ((> c a) (square-sum-larger c b a))
        (else (+ (* a a)
                 (* b b)))))
*/

</script>
</div>

<p>

<div class='exercise'>

<p> <b> Exercise 1.4. </b> 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:

<div id="scheme-ex-14" class="static">
(define (mystery a b)
  ((if (> b 0) + -) a b))
</div>

<p> Describe the behavior of the procedure by selecting which descriptions are equivalent. If you think that the procedure definition is invalid, choose the reasons why.

<div id="scheme-ex-14-mcq"></div>
<script>
C.make_MCQ("scheme-ex-14-mcq",
    ["<tt>(if (> b 0) (+ a b) (- a b))</tt>",
     "<tt>(+ a (if (> b 0) b (- b)))</tt>",
     "<tt>(+ a (abs b))</tt>"],
    ["Error: the leftmost subexpression is not a procedure",
     "Error: the value of the leftmost subexpresion cannot depend on b",
     "Error: the leftmost subexpression is not evaluated in the substitution model"
     ]);
</script>

</div>
<script>
C.make_static("scheme-ex-14");
//
</script>

<p>

<div class='exercise'>

<p> <b> Exercise 1.5. </b> 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:

<div id="scheme-ex-15-p" class="static">
(define (p) (p))

(define (test x y)
  (if (= x 0)
      0
      y))
</div>

<p> Then he evaluates the expression

<div id="scheme-ex-15-test" class="static">
(test 0 (p))
</div>

<p> 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.)

<div id="scheme-ex-15-mcq"> </div>

<a href='http://community.schemewiki.org/?sicp-ex-1.5' target="_blank"> discussion </a>

</div>
<script>
C.make_static("scheme-ex-15-p");
C.make_static("scheme-ex-15-test");
C.make_MCQ("scheme-ex-15-mcq",
    ["In applicative-order evaluation, <tt>(p)</tt> will be evaluated, resulting in an infinite loop",
     "In normal-order evaluation, <tt>(p)</tt> is not evaluated because predicate of <tt>if</tt> evaluates to <tt>true</tt>"],
    ["In normal-order evaluation, <tt>(p)</tt> will be evaluated, resulting in an infinite loop",
     "In applicative-order evaluation, <tt>(p)</tt> is not evaluated because predicate of <tt>if</tt> evaluates to <tt>true</tt>",
     "Error in both cases: <tt>(p)</tt> cannot be defined in terms of itself",
     "In both cases, <tt>0</tt> is returned because <tt>(p)</tt> evaluates to itself, terminating the recursion"
     ]);
</script>

<a name="%_sec_1.1.7" />
<h3> 1.1.7 Example: Square Roots by Newton's Method </h3>

<p> 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.

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

$$
\text{$\sqrt x$ = the $y$ such that $y \ge 0$ and $y^2 = x$}
$$

<p>  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:

<div id="scheme-pseudo-sqrt">
(define (sqrt x)
  (the y (and (>= y 0)
              (= (square y) x))))
</div>
<script>
C.no_output_frozen_prompt("scheme-pseudo-sqrt");
</script>

<p> This only begs the question.

<p> 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.<a name="footnote_link_1-20" class="footnote_link" href="#footnote_1-20">20</a>

<p> 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
$\frac{x}{y}$.<a name="footnote_link_1-21" class="footnote_link" href="#footnote_1-21">21</a> For example, we can compute the square root of 2 as follows. Suppose our initial guess is $1$:<p>

\begin{array}{c|c|c}
\text{Guess} &amp; \text{Quotient} &amp; \text{Average} \\
\hline \\
1       &amp; \frac{2}{1} = 2            &amp; \frac{1}{2} (2 + 1) = 1.5 \\
1.5     &amp; \frac{2}{1.5} = 1.3333     &amp; \frac{1}{2} (1.3333 + 1.5) = 1.4617 \\
1.4617  &amp; \frac{2}{1.4617} = 1.4188  &amp; \frac{1}{2} (1.4167 + 1.4188) = 1.4142 \\
1.4142  &amp; \frac{2}{1.4142} = 1.4164  &amp; \cdots
\end{array}

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

<p> 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:

<div id="scheme-define-sqrt-iter">
(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
                 x)))
</div>
<script>
C.prompt("scheme-define-sqrt-iter", ["scheme-define-good-enough", "scheme-define-improve"]);
</script>

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

<div id="scheme-define-improve">
(define (improve guess x)
  (average guess (/ x guess)))
</div>
<script>
C.prompt("scheme-define-improve", ["scheme-define-average"]);
</script>

<p> where

<div id="scheme-define-average">
(define (average x y)
  (/ (+ x y) 2))
</div>
<script>
C.prompt("scheme-define-average");
</script>

<p> 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):<a name="footnote_link_1-22" class="footnote_link" href="#footnote_1-22">22</a>

<div id="scheme-define-good-enough">
(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))
</div>
<script>
C.prompt("scheme-define-good-enough", ["scheme-define-square"]);
</script>

<p> Finally, we need a way to get started. For instance, we can always guess that the square root of any number is 1:<a name="footnote_link_1-23" class="footnote_link" href="#footnote_1-23">23</a>

<div id="scheme-define-sqrt">
(define (sqrt x)
  (sqrt-iter 1.0 x))
</div>
<script>
C.prompt("scheme-define-sqrt", ["scheme-define-sqrt-iter"]);
</script>

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

<div id="scheme-sqrt-9">
(sqrt 9)
</div>
<script>
C.prompt("scheme-sqrt-9", ["scheme-define-sqrt"]);
</script>

<p>

<div id="scheme-sqrt-plus">
(sqrt (+ 100 37))
</div>
<script>
C.prompt("scheme-sqrt-plus", ["scheme-define-sqrt"]);
</script>

<p>

<div id="scheme-sqrt-sqrt">
(sqrt (+ (sqrt 2) (sqrt 3)))
</div>
<script>
C.prompt("scheme-sqrt-sqrt", ["scheme-define-sqrt"]);
</script>

<p>

<div id="scheme-square-sqrt">
(square (sqrt 1000))
</div>
<script>
C.prompt("scheme-square-sqrt", ["scheme-define-square", "scheme-define-sqrt"]);
</script>

<p> 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.<a name="footnote_link_1-24" class="footnote_link" href="#footnote_1-24">24</a>

<div class="exercise">

<p> <b> Exercise 1.6. </b> Alyssa P. Hacker doesn’t see why <tt>if</tt> needs to be provided as a special form. “Why can’t I just define it as an ordinary procedure in terms of <tt>cond?</tt>” she asks. Alyssa’s friend Eva Lu Ator claims  this can indeed be done, and she defines a new version of <tt>if</tt>:

<div id="scheme-define-new-if">
(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))
</div>

<p> Eva demonstrates the program for Alyssa:

<div id="scheme-new-if-1">
(new-if (= 2 3) 0 5)
</div>

<p>

<div id="scheme-new-if-2">
(new-if (= 1 1) 0 5)
</div>

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

<div id="scheme-sqrt-iter-new-if">
(define (sqrt-iter guess x)
  (new-if (good-enough? guess x)
          guess
          (sqrt-iter (improve guess x) x)))
</div>

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

<div id="scheme-new-if-mcq"> </div>
<a href='http://stackoverflow.com/questions/1171252/whats-the-explanation-for-exercise-1-6-in-sicp' target="_blank"> discussion </a>
</div>
<script>
C.prompt("scheme-define-new-if");
C.prompt("scheme-new-if-1", ["scheme-define-new-if"]);
C.prompt("scheme-new-if-2", ["scheme-define-new-if"]);

C.make_static("scheme-sqrt-iter-new-if");

C.make_MCQ("scheme-new-if-mcq",
    ["Infinite loop: sqrt-iter always evaluates itself"],
    ["It works as before",
     "Infinite loop: cond evaluates all its arguments",
     "Error: only <tt>if</tt> can perform conditional evaluations"
    ]);
</script>

<p>

<div class="exercise">
<p> <b>Exercise 1.7. </b> The <tt>good-enough?</tt> 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.

<p> An alternative strategy for implementing <tt>good-enough?</tt> 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?

<div id="scheme-ex-17-input" class='input'>
(define (my-sqrt x)
  'your-code-here 42)
</div>

<p>

<div id="scheme-ex-17-test">
(square (sqrt 0.0009))
</div>

<p>

<div id="scheme-ex-17-my-test">
(square (my-sqrt 0.0009))
</div>

<script>
C.add_output("scheme-ex-17-input");
C.make_editable("scheme-ex-17-input").setOption('onBlur', function() {
  C.editor_of["scheme-ex-17-my-test"].getOption("onBlur")(); //needed to push dependencies; TODO make a pushDeps() function
  C.eval_editor("scheme-ex-17-input").then(function(res){
    C.$_("scheme-ex-17-input-output").empty().append($("<span>" + res + "</span>"));
  })
});
C.frozen_prompt("scheme-ex-17-test", ["scheme-define-sqrt"]);
C.frozen_prompt("scheme-ex-17-my-test", ["scheme-define-square", "scheme-ex-17-input"]);
</script>

<!--
(define (square x)
   (* x x))

(define (average x y)
   (/ (+ x y)
      2))

(define (good-enough? guess previous-guess)
   (< (abs (- guess previous-guess))
         0.001))

(define (improve guess x)
   (average guess
            (/ x guess)))

(define (sqrt-iter guess previous-guess x)
   (if (good-enough? guess previous-guess)
       guess
       (sqrt-iter (improve guess x)
                  guess
                  x)))

(define (sqrt x)
   (sqrt-iter 1.0 0 x))
!-->
</div>

<p>

<div class="exercise">

<p> <b> Exercise 1.8. </b> 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

$$
\frac{x/y^2 + 2y}{3}
$$

<p> Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In Section <a href="1-3-hop.html#%_sec_1.3.4">1.3.4</a> we will see how to implement Newton’s  method in general as an abstraction of these square root and cube-root procedures.)

<div id="scheme-ex-18">
(define (cube-root x)
  'your-code-here)
</div>

<p>

<div id="scheme-ex-18-test">
(cube-root 27)
</div>
<script>
C.prompt("scheme-ex-18"); //todo: prompting, etc
C.prompt("scheme-ex-18-test", ["scheme-ex-18"]);

C.editor_of["scheme-ex-18-test"].setOption("readOnly", 'nocursor');
</script>

<!--
(define (cube x)
  (* x x x))

(define (good-enough? guess x)
  (< (abs (- (cube guess) x)) 0.001))

(define (improve guess x)
  (/ (+ (/ x (* guess guess))
        (* 2 guess))
     3))

(define (cube-root-iter guess x)
  (if (good-enough? guess x)
      guess
      (cube-root-iter (improve guess x) x)))

(define (cube-root x)
  (cube-root-iter 1 x))
!-->

</div>

<a name="%_sec_1.1.8" />
<h3> 1.1.8 Procedures as Black-Box Abstractions </h3>

<p> 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 &ldquo;circular&rdquo; 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 <a href="1-2-procedures.html">1.2</a>. But first let's consider some other important points illustrated by the sqrt example.

<p> 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.

<div class="figure">
<img src='images/ch1-Z-G-6.gif'>
<p> <b> Figure 1.2: </b> Procedural decomposition of the <tt>sqrt</tt> program.
</div>

<p> 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 &mdash; 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 &ldquo;black box.&rdquo; 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.

<p> 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.<a name="footnote_link_1-25" class="footnote_link" href="#footnote_1-25">25</a>

<div id="scheme-define-square-times">
(define (square x) (* x x))
</div>

<p>

<div id="scheme-define-square-exp">
(define (double x) (+ x x))

(define (square x)
  (exp (double (log x))))
</div>

<p>

<div id="scheme-define-square-tan">
(define (square x)
  (- 1 (/ (* 2 x) (tan (* 2 (atan x))))))
</div>

<script>
C.prompt("scheme-define-square-times");
C.prompt("scheme-define-square-exp");
C.prompt("scheme-define-square-tan");
</script>

<p> 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.

<h4>Local names</h4>

<p> 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:

<div id="scheme-define-square-x">
(define (square x) (* x x))
</div>

<div id="scheme-define-square-y">
(define (square y) (* y y))
</div>

<script>
C.prompt("scheme-define-square-x");
C.prompt("scheme-define-square-y");
</script>

<p> This principle &mdash; that the meaning of a procedure should be independent of the parameter names used by its author &mdash; 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:

<div id="scheme-define-good-enough-2">
(define (good-enough? guess x)
  (&lt; (abs (- (square guess) x)) 0.001))
</div>
<script>
C.make_static("scheme-define-good-enough-2");
</script>

<p> 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.

<p> 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.

<p> 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.<a name="footnote_link_1-26" class="footnote_link" href="#footnote_1-26">26</a> 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.

<p> In the definition of good-enough? above, guess and x are bound variables but &lt;, -, 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.

<h4>Internal definitions and block structure</h4>

<p> 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:

<div id="scheme-define-sqrt-full">
(define (sqrt x)
  (sqrt-iter 1.0 x))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x) x)))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (improve guess x)
  (average guess (/ x guess)))
</div>
<script>
C.prompt("scheme-define-sqrt-full", ["scheme-define-square", "scheme-define-average"]);
</script>

<p> 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

<div id="scheme-define-sqrt-block">
(define (sqrt x)
  (define (good-enough? guess x)
    (< (abs (- (square guess) x)) 0.001))
  (define (improve guess x)
    (average guess (/ x guess)))
  (define (sqrt-iter guess x)
    (if (good-enough? guess x)
        guess
        (sqrt-iter (improve guess x) x)))
  (sqrt-iter 1.0 x))
</div>
<script>
C.prompt("scheme-define-sqrt-block", ["scheme-define-square", "scheme-define-average"]);
</script>

<p> 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.<a name="footnote_link_1-27" class="footnote_link" href="#footnote_1-27">27</a>

<div id="scheme-define-sqrt-no-x">
(define (sqrt x)
  (define (good-enough? guess)
    (< (abs (- (square guess) x)) 0.001))
  (define (improve guess)
    (average guess (/ x guess)))
  (define (sqrt-iter guess)
    (if (good-enough? guess)
        guess
        (sqrt-iter (improve guess))))
  (sqrt-iter 1.0))
</div>
<script>
C.prompt("scheme-define-sqrt-no-x", ["scheme-define-square", "scheme-define-average"]);
</script>

<p> We will use block structure extensively to help us break up large programs into tractable pieces.<a name="footnote_link_1-28" class="footnote_link" href="#footnote_1-28">28</a> 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.
@@

{{footnotes}}
<div id="footnote_1-4" class="footnote">
<p> <a href="#footnote_link_1-4" class="footnote_backlink">4</a> The characterization of numbers as &ldquo;simple data&rdquo; 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 <em>integers</em>, such as $2$, from <em>real numbers</em>, 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 &mdash; 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.
</div>

<div id="footnote_1-5" class="footnote">
<p><a href="#footnote_link_1-5" class="footnote_backlink">5</a>
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 slanted characters.
</p></div>

<div id="footnote_1-6" class="footnote">
<p><a href="#footnote_link_1-6" class="footnote_backlink">6</a>
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.
</p></div>

<div id="footnote_1-7" class="footnote">
<p><a href="#footnote_link_1-7" class="footnote_backlink">7</a>
 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 &ldquo;Lisp programmers know the value of everything but the cost of nothing.&rdquo;
</p></div>

<div id="footnote_1-8" class="footnote">
<p><a href="#footnote_link_1-8" class="footnote_backlink">8</a>
 In this book, we do not show the interpreter's response to evaluating definitions, since this is highly implementation-dependent.
</p></div>

<div id="footnote_1-9" class="footnote">
<p><a href="#footnote_link_1-9" class="footnote_backlink">9</a>
 Chapter&nbsp;3 will show that this notion of environment is crucial, both for understanding how the interpreter works and for implementing interpreters.
</p></div>

<div id="footnote_1-10" class="footnote">
<p><a href="#footnote_link_1-10" class="footnote_backlink">10</a>
 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 <tt>+</tt> or <tt>*</tt> 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.
</p></div>

<div id="footnote_1-11" class="footnote">
<p><a href="#footnote_link_1-11" class="footnote_backlink">11</a>
 Special syntactic forms that are simply convenient alternative surface structures for things that can be written in more uniform ways are sometimes called <em>syntactic sugar</em>, 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 &ldquo;convenient&rdquo; 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, &ldquo;Syntactic sugar causes cancer of the semicolon.&rdquo;
</p></div>

<div id="footnote_1-12" class="footnote">
<p><a href="#footnote_link_1-12" class="footnote_backlink">12</a>
 Observe that there are two different operations being combined here: we are creating the procedure, and we are giving it the name <tt>square</tt>. It is possible, indeed important, to be able to separate these two notions &mdash; 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&nbsp;<a href="1-3-hop.html#%_sec_1.3.2">1.3.2</a>.
</p></div>

<div id="footnote_1-13" class="footnote">
<p><a href="#footnote_link_1-13" class="footnote_backlink">13</a>
 Throughout this book, we will describe the general syntax of expressions by using italic symbols delimited by angle brackets &mdash; e.g., &lt;<em>name</em>&gt; &mdash; to denote the &ldquo;slots&rdquo; in the expression to be filled in when such an expression is actually used.
</p></div>

<div id="footnote_1-14" class="footnote">
<p><a href="#footnote_link_1-14" class="footnote_backlink">14</a>
 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.
</p></div>

<div id="footnote_1-15" class="footnote">
<p><a href="#footnote_link_1-15" class="footnote_backlink">15</a>
 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 <em>substitution</em> in the literature of logic and programming semantics. See Stoy 1977 for a careful discussion of substitution.
</p></div>

<div id="footnote_1-16" class="footnote">
<p><a href="#footnote_link_1-16" class="footnote_backlink">16</a>
 In chapter&nbsp;3 we will introduce <em>stream processing</em>, which is a way of handling apparently &ldquo;infinite&rdquo; data structures by incorporating a limited form of normal-order evaluation. In section&nbsp;<a href="4-2-lazy.html#%_sec_4.2">4.2</a> we will modify the Scheme interpreter to produce a normal-order variant of Scheme.
</p></div>

<div id="footnote_1-17" class="footnote">
<p><a href="#footnote_link_1-17" class="footnote_backlink">17</a>
 &ldquo;Interpreted as either true or false&rdquo; means this: In Scheme, there are two distinguished values that are denoted by the constants <tt>#t</tt> and <tt>#f</tt>. When the interpreter checks a predicate's value, it interprets <tt>#f</tt> as false. Any other value is treated as true. (Thus, providing <tt>#t</tt> is logically unnecessary, but it is convenient.)  In this book we will use names <tt>true</tt> and <tt>false</tt>, which are associated with the values <tt>#t</tt> and <tt>#f</tt> respectively.
</p></div>

<div id="footnote_1-18" class="footnote">
<p><a href="#footnote_link_1-18" class="footnote_backlink">18</a> <tt>abs</tt> also uses the &ldquo;minus&rdquo; operator <tt>-</tt>, which, when used with a single operand, as in <tt>(-&nbsp;x)</tt>, indicates negation.
</p></div>

<div id="footnote_1-19" class="footnote">
<p><a href="#footnote_link_1-19" class="footnote_backlink">19</a>
 A minor difference between <tt>if</tt> and <tt>cond</tt> is that the <tt><em>&lt;e&gt;</em></tt> part of each <tt>cond</tt> clause may be a sequence of expressions. If the corresponding <tt><em>&lt;p&gt;</em></tt> is found to be true, the expressions <tt><em>&lt;e&gt;</em></tt> are evaluated in sequence and the value of the final expression in the sequence is returned as the value of the <tt>cond</tt>. In an <tt>if</tt> expression, however, the <tt><em>&lt;consequent&gt;</em></tt> and <tt><em>&lt;alternative&gt;</em></tt> must be single expressions.
</p></div>

<div id="footnote_1-20" class="footnote">
<p><a href="#footnote_link_1-20" class="footnote_backlink">20</a>
 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 &ldquo;correct&rdquo; 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 &ldquo;what is&rdquo; knowledge specified by the programmer, they can generate &ldquo;how to&rdquo; 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&nbsp;4.
</p></div>

<div id="footnote_1-21" class="footnote">
<p><a href="#footnote_link_1-21" class="footnote_backlink">21</a>
 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 <font size="-2">A</font>.<font size="-2">D</font>. We will see how to express the general Newton's method as a Lisp procedure in section&nbsp;<a href="1-3-hop.html#%_sec_1.3.4">1.3.4</a>.
</p></div>

<div id="footnote_1-22" class="footnote">
<p><a href="#footnote_link_1-22" class="footnote_backlink">22</a>
 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.
</p></div>

<div id="footnote_1-23" class="footnote">
<p><a href="#footnote_link_1-23" class="footnote_backlink">23</a>
 Observe that we express our initial guess as $1.0$ rather than $1$. This would not make any difference in many Lisp implementations. MIT Scheme, however, distinguishes between exact integers and decimal values, and dividing two integers produces a rational number rather than a decimal. For example, dividing $10$ by $6$ yields $5/3$, while dividing $10.0$ by $6.0$ yields $1.6666666666666667$. (We will learn how to implement arithmetic on rational numbers in section&nbsp;<a href="2-1-data.html#%_sec_2.1.1">2.1.1</a>.)  If we start with an initial guess of $1$ in our square-root program, and $x$ is an exact integer, all subsequent values produced in the square-root computation will be rational numbers rather than decimals. Mixed operations on rational numbers and decimals always yield decimals, so starting with an initial guess of $1.0$ forces all subsequent values to be decimals.
</p></div>

<div id="footnote_1-24" class="footnote">
<p><a href="#footnote_link_1-24" class="footnote_backlink">24</a>
 Readers who are worried about the efficiency issues involved in using procedure calls to implement iteration should note the remarks on &ldquo;tail recursion&rdquo; in section&nbsp;<a href="1-2-procedures.html#%_sec_1.2.1">1.2.1</a>.
</p></div>

<div id="footnote_1-25" class="footnote">
<p><a href="#footnote_link_1-25" class="footnote_backlink">25</a>
 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 &ldquo;obvious&rdquo; implementation is the less efficient one. Consider a machine that has extensive tables of logarithms and antilogarithms stored in a very efficient manner.
</p></div>

<div id="footnote_1-26" class="footnote">
<p><a href="#footnote_link_1-26" class="footnote_backlink">26</a>
 The concept of consistent renaming is actually subtle and difficult to define formally. Famous logicians have made embarrassing errors here.
</p></div>

<div id="footnote_1-27" class="footnote">
<p><a href="#footnote_link_1-27" class="footnote_backlink">27</a>
 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&nbsp;3 when we study environments and the detailed behavior of the interpreter.
</p></div>

<div id="footnote_1-28" class="footnote">
<p><a href="#footnote_link_1-28" class="footnote_backlink">28</a>
 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.
</p></div>
@@
