Monday, 30 January 2012

Greatest Common Divisor

The code that works out the greatest common divisor looks like this:

(fn [x y]
    (> x y) (recur (- x y) y)
    (< x y) (recur (x (- y x))
    :else x))

Within a cond construction you don't have to put the pair of forms for a condition and a corresponding action in a list of their own like in Scheme, which saves some typing, so long as you don't lose count. The :else in there is not anything special, it's just convenient in that as a symbol it evaluates to true in a boolean context. And we note the use of the recur function without a loop: in this case control loops back to the start of the enclosing function definition, thereby saving a bit more typing.

No comments:

Post a Comment