π

The Little Schemer. ch 4. part 2. subtracting natural numbers

Show Sidebar

How do we define subtraction in terms of sub1? Based on the content of this book so far, it's likely got something to do with recursion.

Again, going from the solution to o+ we can guess that we'll be asking a series of questions with cond, and that we'll start by checking for 0. We know that there'll be 2 arguments, n and m. We'll need to subtract m from n, and we'll need to stop when one of them hits 0. This kinda tells us that both arguments are gonna need to be subtracted.

If we were using real numbers, I'd be worried here because we only have sub1 to work with, and negative numbers make that complex - but with natural numbers, subtracting both works just fine. We'll never have to deal with 6 - -3 or whatever.

In essence, what we need to do here is (sub1 n) =m= times. Let's give that a go:

o-

(define o-
  (lambda (n m)
    (cond
      ((zero? m) n)
      (else (o- (sub1 n) (sub1 m))))))


(o- 14 3)
(o- 17 9)	  

#+RESULTS: o-

 11
 8	  

That seems to work pretty well. Looking at the definition in the book, there's the same pattern again - they define o- in the same way that I have, but the last line is

 (else (sub1 (o- n (sub1 m))))	  

I'm a little concerned that I'm missing some point or other here, but it could be just that I think in a different way. I'm gonna leave it, and hope that it doesn't come back to bite me!

Comment via email or via Disqus comments below: