I am learning Scheme using DrRacket R5RS. I thought that I was nailing down the concepts, but I cannot get this simple recursion exercise to work. I think that it is a bug in DrRacket, but I'm not sure.
Can someone see the problem and, hopefully, explain why my code does not work? I really want to learn this functional language.
This code will produce #T and #F correctly:
(define three (lambda (L target1 target2 target3 sum)
(cond
((= target1 0) (three L (car L) (cadr L) (caddr L) 0))
((NULL? L) (= (- sum (+ target1 (+ target2 target3))) (+ target1 (+ target2 target3)))) ; sum minus targets = targets
(else (three (cdr L) target1 target2 target3 (+ sum (car L)))) ; return true if branch returns true
)))
When I launch the program with (three '(1 2 3 6) 0 0 0 0), it returns #T since 1+2+3=6. When I launch the program with (three '(1 2 3 5) 0 0 0 0), it returns #F since 1+2+3!=5.
Now, here is the problem. I want to do multi-branch recursion. However, this code returns #T every single time! Since I cannot get it to return #F, I cannot get it to skip to the next branch of my recursion.
(define three (lambda (L target1 target2 target3 sum)
(cond
((= target1 0) (three L (car L) (cadr L) (caddr L) 0))
((NULL? L) (= (- sum (+ target1 (+ target2 target3))) (+ target1 (+ target2 target3)))) ; sum minus targets = targets
((three (cdr L) target1 target2 target3 (+ sum (car L))) #T) ; return true if branch returns true
(else 'hit_the_bottom) ; IT NEVER HITS THIS STATEMENT!
)))
Any ideas?
(else #f)and it'll work. To see why, take a look at my answer below. - Óscar López