Question

I just start to learn Scheme today.

I wrote a function gcd(), but it always returns 0.

(define (gcd a b)
    (cond (= b 0) 
        (a)
     (else ((gcd b (modulo a b))))
    )
)

Why I am wrong?

Was it helpful?

Solution

This should fix the problems:

(define (gcd a b)
  (cond [(= b 0) a]
        [else (gcd b (modulo a b))]))

You were incorrectly surrounding some expressions between parenthesis, and some parenthesis were missing from the cond expression.

Notice that in Scheme, when you surround something in parenthesis, say (a) you're telling the interpreter: a is a procedure with no arguments and I want to call it, and this was not the case in here, a is just a number.

Also, for readability's sake, it's a good idea to use [] instead of () to separate each of the conditions in a cond expression, as shown in my code above - but don't forget them, they're mandatory and in your code you forgot them in the first condition.

OTHER TIPS

Other people have described what your mistake is and what you should do.

It is also instructive to consider how your code is actually run and why it produces the output you see. Because of your missing parentheses, the first case for your cond is (= b 0). The first thing (=) is taken as the condition. Everything in Scheme except #f is true, so this is always true. Since it is true, this case is evaluated. Specifically, the rest of the things in the parentheses is taken as (possible multiple) expressions to evaluate, as an implicit begin. So basically it evaluates (begin b 0). The result is the result of the last expression, 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top