Quirksand

SICP

SICP 1.3.2 Exercises

November 3, 2013 15:53

This is a very brief section with only one exercise, and it’s actually just something to test the interpreter with. Therefore there is only an exercise file for this section, and I’ll discuss the results right here. So if you’d rather figure it out yourself, go and play with it first.

Ex 1.34.

The observed behavior is an error; in Dr Racket’s case I get this message:

procedure application: expected procedure, given: 2; arguments were: 2

Of course it’s never enough to know that you’ve produced an error. What’s important is to know what the error means and what caused it.

As to what it means, the message is slightly obtuse but can be straightforwardly unpacked to make sense. What happened is that the interpreter (here called the ‘application’) was expecting to execute a procedure and did not get one. It says that it was given 2 instead of a procedure. There is a bit of additional helpful information in saying arguments were: 2; what that tells us is that the expected procedure was passed an argument list of 2. From this we know that somewhere, instead of a procedure with an argument of 2, we have something that either says or was evaluated as (2 2). For comparison, try simply entering the line (2 2) by itself and you should see the same error.

Examining the code, it’s obvious that there is no direct statement (2 2). Rather than try to work back from the error, in this case we’ll go forward from the statement (f f) to figure out just what it does and see if it leads us to the error, since we know it was at this statement that it occurred.

The procedure f takes one argument g. That argument is then used as a procedure and called with the argument 2. In the earlier statement, such as with square (sqr in the Racket dialect), g is equal to square and the result is the same as (square 2), which as expected yields 4. Thus when we call (f f), we use f as our argument g, in other words it evaluates to (f 2). Then we have to go back into f, this time with 2 as our argument. That means it evaluates to (2 2). This is then what leads to the error.

To verify this, enable the trace statement and see how the procedure f is called.

Exercises 1.3.2