Function template for functions whose value is a natural number

If the function necessarily returns a natural number (i.e. the question that the function asks couldn't possibly have a negative or non-integer answer, such as "how many?"), 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)). Since there are two possible choices for the output, the body will be a cond with two cases:
(define (function-returning-nat-num ...)
   (cond [... 0]
         [... (add1 some-nat-num)]))
(As usual, the order of clauses may be different from this, but 95% of the time you want the simplest return value, 0, to appear in the first clause.)

Where you get some-nat-num can vary. Notice that it's the same data type that function-returning-nat-num returns, so a very common way to get it is by calling function-returning-nat-num on something else.

(define (function-returning-nat-num ...)
   (cond [... 0]
         [... (add1 (function-returning-nat-num ...))]))

Last modified: Thu Dec 12 14:01:58 EST 2002 Stephen Bloch / sbloch@adelphi.edu