I'm new to Clojure but I already know about functions and lists, so I decided to implement Prime Factors Kata solution. For any natural number the function should return a list of all its prime factors, e.g. for 15 it should return (3 5).
It turned out that to implement a stack safe function I needed to use loop
and recur
, which I was not familiar with.
So, does my solution look like idiomatic Clojure? What could be improved? Thanks!
(defn primeFactorsOf
"Return all prime factors of a number"
[n]
(loop [number n candidate 2 factors ()]
(if (= number 1)
(reverse factors)
(if (= (mod number candidate) 0)
(recur (/ number candidate) candidate (conj factors candidate))
(recur number (inc candidate) factors)))))