سؤال

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

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top