CS 61A
Week 1
Homework Solutions
1.
The Scheme interpreter applies an ordinary procedure by first evaluating
all the argument expressions and then invoking the procedure.
Consider first
one of the examples that worked:
> (newif (= 2 3) 0 5)
Scheme evaluates this expression as follows:
(a) Evaluate the symbol newif.
Its value turns out to be an ordinary
procedure.
Therefore the rest of the combination is evaluated normally.
(b) Evaluate the three argument expressions.
Their values are #f [i.e.,
false], 0, and 5 respectively.
(c) Apply the procedure newif to the argument values #f, 0, and 5.
By the
substitution model, this means we must substitute "#f" for "predicate",
"0" for "thenclause", and "5" for "elseclause":
(cond (#f 0) (else 5))
(d) Evaluate this new expression, getting the value 5.
By contrast, if we'd entered the expression
> (if (= 2 3) 0 5)
Scheme would evaluate it as follows:
(a) Notice that the symbol IF is a keyword, the name of a special form.
Therefore the rest of the combination is evaluated specially.
(b) Invoke the special form with the UNEVALUATED argument expressions
"(= 2 3)", "0", and "5".
(c) The "if" evaluation rule then causes its first argument to be
evaluated.
Since the value is #f, i.e. false, it then evaluates
the expression "5", whose value is the number 5.
The expression "0"
is never evaluated.
In the example above, it doesn't make any PRACTICAL difference that the
expression "5" was evaluated to produce the number 5.
[By the way,
Scheme uses quotation marks for a special purpose, which isn't what I
mean here.
I'm just using them to delimit something you're to imagine as
having typed into the computer.]
Now, on to the square root program.
In the body of sqrtiter, the third and
final argument to newif is the expression
(sqrtiter (improve guess x) x)
Suppose we invoke sqrtiter with an expression like
(sqrtiter 1 4)
Since sqrtiter and newif are both ordinary procedures, they are applied
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '08
 Harvey
 Expression

Click to edit the document details