SICP 3.1.3 Exercises

July 16, 2017 11:05

There are only two exercises here. The first one is an extension to code from previous exercises (Section 3.1.1 specifically). If you have not completed all the exercises for that section, you’ll need to do so, or download the solution file. The tests also rely on check-eqv? defined as it was in that file, so make sure it exists either in the included file, or that you copy it to a new one. It’s a good idea to preserve the old file as-is and it include it entirely, with all its tests, so that if it inadvertently gets altered, it’ll be easier to determine where the error lies.

The second exercise initially seems difficult to test, since it asks for a function that changes its result depending on which order the arguments are evaluated in. In order to test it based on what we know how to do, there are two possible approaches. We’ll learn other ways to change evaluation order later One option is just to change the expression itself, so that (+ (f 0) (f 1)) is compared with (+ (f 1) (f 0)). It turns out that the Scheme language does not actually specify a particular order of argument evaluation. That means that while proper solutions to this exercise will show a difference, there’s no way, using this method, to tell which one is actually ‘right-to-left’ or ‘left-to-right’. A second approach is to use nested let statements. Each let works to evaluate an ‘argument’ as a variable, and by changing the order of nesting, the order of evaluation is changed. This will give us a guaranteed order, since this will evaluate the arguments as variables prior to the addition statement. We then capture the output of the let expressions to compare with the expected value. Both methods are included in the exercise file.

There are also some optional considerations in the tests for the second exercise. The problem statement doesn’t clarify if the function only needs to work once, or if it must work at any point in time. Adding more conditions makes the exercise considerably more difficult to solve, so it’s fine to ignore them, as they may not be an intended part of the exercise and thus don’t really need to be tested.

Exercises 3.1.3.