Reputation: 3190
I'm having a hard time getting a simple nested if statement to work. I have two functions divisible2? and divisible3? and I want to see if a certain number - n is divisible by both 2 and 3. Here's what I have so far:
(define (divisible2? x)
(zero? (remainder 2 x))) ;
(define (divisible3? x)
(zero? (remainder 3 x))) ;
(define (div23 n)
(if (divisible2? n)
(if (divisible3? n)) #t (#f))
)
Thanks
Upvotes: 0
Views: 11341
Reputation: 61865
There are several problems. One is that the parenthesis are wrong around the inner-if
such that it has no true-expr or false-expr within the form. The parenthesis around false later on are also problematic. In addition, every if
should have both true-expr and false-expr supplied (although this differs in dialects, IIRC).
The symmetric structure can be seen in a corrected expanded form.
(if (divisible2? n) ; outer if-expr
(if (divisible3? n) ; outer then-expr (and inner if-expr)
#t ; inner then-expr
#f) ; inner else-expr
#f) ; outer else-expr
Alternatively, simply use and
.
(and (divisible2? n) (divisible3? n))
And you could make the divisible?
functions take in the "divisible by" value.
Upvotes: 3