I have written the following code for calculating the Greatest Common Divisor of two positive numbers. Are there some matters in the code which are not optimal or clojurian enough, and if so what would be the more cloujerian way of doing GCD?
(def gcd (fn [a b] (->> (map (fn [x]
(filter #(zero? (mod x %)) (range 1 (inc x))))
[a b])
(map set)
(apply clojure.set/intersection)
(apply max))))
(gcd 1023 858)` => 33
using sequence manipulation for numeric operations (without transducers) is a bit heavyweight and this would be a great case for recur
instead:
user> (defn gcd [a b]
(if (zero? b)
a
(recur b (mod a b))))
#'user/gcd
user> (gcd 1023 858)
33
This saves some effort/time that would go into building sequences that are then discarded. In this case it creates a secuence of two sequences of numbers, turns that into a sequence of two sets, then smashes that down into single set from which the largest value is the answer.
Also, in general, when defining vars containing functions use defn
(short for define function) it adds nice things automatically that help the tooling a lot, like displaying argument types and such.