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:(An equivalent way to write
a natural number is either
0
, or(add1 natural-number)
(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 ...))]))