Function template for natural-number parameter

If one of the input parameters is necessarily a natural number (by which I mean that the function wouldn't make sense on a negative number or a non-integer), use the "several possible cases" template, combined with the fact that non-zero natural numbers "have" a predecessor which is itself a natural number.

Data definition:
a natural number is either
  1. 0 , or
  2. (add1 natural-number)
(An equivalent way to write (add1 natural-number) is (+ 1 natural-number)). So the body will be a cond with two cases:
(define (template-for-nat-num n)
   (cond [(= n 0) ...]
         [(> n 0) ...]))
Furthermore, if the natural number is positive, you know that it has a predecessor, so by the "compound data type" rule you can expand the template to
(define (template-for-nat-num n)
   (cond [(= n 0) ...]
         [(> n 0) 
	  ... n ...
	  ... (sub1 n) ...            ; or equivalently (- n 1)
	 ]))
In the (> n 0) cond-clause, we know that n is positive, so (sub1 n) is a natural number too, which is the same type we started with. So the most likely thing to do with "(sub1 n)" is to apply the same function to it:
(define (template-for-nat-num n)
   (cond [(= n 0) ...]
         [(> n 0) 
	  ... n ...
	  ... (sub1 n) ...            ; or equivalently (- n 1)
	  ... (template-for-nat-num (sub1 n))
	  ]))

Last modified: Thu Dec 12 13:53:12 EST 2002
Stephen Bloch / sbloch@adelphi.edu