Search code examples
clojure

How is recur being used here? [Clojure]


I thought I understood recur, but the following usage doesn't make sense:

(fn gcd [a b] 
    (if (= b 0) 
        a 
        (recur b (rem a b))))  

The function retrieves the greatest common divisor for two numbers. For 4 and 2, the function would give 2.

I know that recur can be bound to functions, but I would think that 'b' is just cycled through the recur without any change. You generally need to put in something like a (inc b) to allow the value in the loop to change.

What am I missing?


Solution

  • The gcd function here uses the Euclidean algorithm to find the Greatest Common Divisor of two numbers.

    The function works and does terminate because the argument list contains [a b] but the recur is called for b, (rem a b). Note that the place of b is changed here (from seond place to first place).

    The value of a is changed because the value of b is assigned to it. Also, the value of b is changed because (rem a b) is assigned to it (thus decreasing). Therefore both values decrease when the calls are repeated and eventually one of them reaches 0 (that stops the recursion).