Style: Bomb-proof Code

The code for factorial was given earlier:


   (define (fact n)
     (if (= n 0)
         1
         (* n (fact (- n 1))) ) )
This is fine provided that it is given a good argument n. But what happens if n is negative: (fact -3) ?

Rule: Test for a half-space rather than just for a point. It costs no more and can prevent errors.

Rule: Don't assume good input. Test it.


   (define (factorial n)
     (if (<= n 0)
         1
         (* n (factorial (- n 1))) ) )

Contents    Page-10    Prev    Next    Page+10    Index