Exercise

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:

1
2
(define (a-plus-abs-b a b)
  ((if (> b 0) + -) a b))

Student Response

Predicate:

1
(> b 0) 

Consequent:

1
+

Alternative:

1
-

So that means that if b is greater than 0, then we add a and b, otherwise we subtract b from a. We can use compound expressions as operators in procedures.

Teacher Evaluation

Evaluation

Critique my description of the behavior. Provide notes on what I am overlooking.

Your description is mostly correct but could be more precise and complete. Here are the key points to consider:

  1. Operator Selection: You correctly identified that the if expression selects between + and - operators, but it might be worth explicitly stating that the entire (if (> b 0) + -) expression evaluates to either the addition or subtraction operator, which is then immediately applied to a and b.

  2. Function Purpose: The name of the function a-plus-abs-b gives us a clue that you didn’t mention - it’s computing a plus the absolute value of b. This is achieved by:

    • When b > 0: a + b (which is a plus |b| when b is positive)
    • When b ≤ 0: a - b (which is a plus |b| when b is negative, since negative minus negative equals positive)
  3. Complete Predicate: Your predicate description should note that when b = 0, it falls into the negative case (using -). The condition is strictly b > 0, not b ≥ 0.

  4. Compound Expression: While you mentioned that compound expressions can be operators, you might want to emphasize that this is a particularly clever use of this feature - it’s using the result of an if expression as the operator itself, demonstrating how Scheme treats operators as first-class values that can be the result of any expression.

A more complete description might be: “This procedure computes a plus the absolute value of b by using a compound expression as the operator. The if expression evaluates to either the addition (+) or subtraction (-) operator based on whether b is positive. When b is positive, it adds a and b; when b is zero or negative, it subtracts b from a, effectively adding its absolute value.”