Quirksand

SICP

SICP 2.2.2 Exercises

June 25, 2014 15:27

Having established the useful building block of the list, we move on to more complex structures. This section shows how to build and use a tree and similar structures. We start by looking at how they’re actually built (using lists), and then get on to using them. For the later exercises it can be understood that when working with these structures we don’t always have to know how they’re built. In LISP just about everything is built from lists, which makes it simple, but other languages can and do implement them differently.

There are a number of testing methods used here; almost a different style in each exercise. In exercise 2.25 we make use of a special function that simply tests whether an expression is equal to 7.

(define (equal-7? expr)
  (display 
   (if (number? expr)
       (if (= expr 7)
           "correct"
           expr
           )
      expr
      )
   )
  (newline)
  )

In case it’s not clear, this outputs ‘correct’ if the expression equals 7, but if it is not, it will output the expression itself. That’s one way to give us a result (assuming that ‘correct’ is not the wrong expression passed in) that also provide useful information if the value is wrong. The number? predicate is used to first determine if the expression is even a number, otherwise an error might occur, halting execution.

The tests in 2.29 are used for two versions of a function. They can be exactly the same even when we change the underlying constructor, as the tests only make use of the higher-level procedures. For these tests, I also used a couple of simple procedures that let us know if we’re passing or failing according to how the mobiles should balance.

(define (test-true x) (displayln (if x "passed" "failed")))
(define (test-false x) (displayln (if (not x) "passed" "failed")))

Give test-true an expression x, and if x evaluates to true, it will say the test passed. If not, you’re told that it failed. The false version makes it easy to check an expression we expect to be false. These are pretty rudimentary, but they save us a bit of time, and if you want to modify them to display a different value (say, in your own language), you can, and then all the places that use them will work the same way, so hopefully it does provide some help.

The last exercise in the section (2.32) presents a bit of a challenge for testing. The requested procedure creates a set whose elements are known, but I can’t predict in advance what the exact result is going to be. It’s a list with no particularly defined order, so just comparing it to an expected answer list might label a correct result as a failure. It’s not an impossible task to test this; I just felt it a bit more than was necessary to jump into at this stage of the book. You may wish to consider how to work it out, or come back to this after finishing Chapter 2, at which point you’ll likely have a better understanding of how to implement it.

Exercises 2.2.2