I'm going through Simply Scheme and just got to the section on recursion.
I don't understand why when the base case is met Scheme returns the "built up" value of the recursive procedure and not the actual argument value which caused the base case to evaluate to #t.
For example, have a look at this sample code snippet of a recursive procedure which takes a word as input, reverses it, and spits it back out:
(define (reverse wd)
(if (empty? wd) wd
(word (last wd) (reverse (bl wd)))))
Here's what confuses me: (if (empty? wd) wd
I understand that when the actual argument value for the formal parameter wd is empty (or "") the base case evaluates to #t, causing the value of the second argument to if to be evaluated.
What I don't understand is how the second argument to if (wd, in this case) can return something that's not empty even though it would appear to be the same, empty, formal parameter that triggered the base case.
What am I missing?
If there's something in the documentation (or the text) which explains this I'd be happy to review it.
(if test then-part else-part)isthen-partiftestis true, andelse-partiftestis false. So wheneverwdis empty, you are returningwd(which is empty). Wheneverwdis not empty, though, you're returning(word (last wd) (reverse (bl wd))). Do you see why that won't be empty whenwdisn't empty? Even without considering(reverse (bl wd)), and just looking at(word (last wd) …)we see something non-empty since(last wd)is something and(word <something> …)is a string beginning with<something>. - Joshua Taylor