I’m working my way through How to Design Programs on my own. I haven’t quite grasped complex linear recursion, so I need a little help.
The problem:
Define multiply, which consumes two natural numbers, n and x, and produces n * x without using Scheme’s *. Eliminate + from this definition, too.
Straightforward with the + sign:
(define (multiply n m)
(cond
[(zero? m) 0]
[else (+ n (multiply n (sub1 m)))]))
(= (multiply 3 3) 9)
I know to use add1, but I can’t it the recursion right.
Thanks.
Split the problem in two functions. First, you need a function
(add m n)which adds m to n. What is the base case? when n is zero, return m. What is the recursive step? add one to the result of callingaddagain, but decrementing n. You guessed it,add1andsub1will be useful.The other function,
(mul m n)is similar. What is the base case? if either m or n are zero, return 0. What is the recursive step? add (using the previously defined function) m to the result of callingmulagain, but decrementing n. And that’s it!