In Racket, we use recursion very frequently. Here is an example of a function that sums all of the numbers from zero to the parameter, n
.
(define (sum n)
(if (zero? n)
0
(+ n (sum (sub1 n)))))
Note that there are many helpful convenience based functions used here, such as zero?
and sub1
. Each respectively does just what you might expect: zero?
returns a boolean which says whether the given number was equal to zero, and sub1
subtracts one from its argument.