{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# hw1 - CS 61A Week 1 Homework Solutions 1 The Scheme...

This preview shows pages 1–2. Sign up to view the full content.

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: > (new-if (= 2 3) 0 5) Scheme evaluates this expression as follows: (a) Evaluate the symbol new-if. 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 new-if to the argument values #f, 0, and 5. By the substitution model, this means we must substitute "#f" for "predicate", "0" for "then-clause", and "5" for "else-clause": (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 sqrt-iter, the third and final argument to new-if is the expression (sqrt-iter (improve guess x) x) Suppose we invoke sqrt-iter with an expression like (sqrt-iter 1 4) Since sqrt-iter and new-if 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.

{[ snackBarMessage ]}