From a41dbbba1bfe9e34a31eb37ae6aaaac8e44b10eb Mon Sep 17 00:00:00 2001 From: Adar Nimrod <nimrod@shore.co.il> Date: Sun, 14 Feb 2016 16:16:49 +0200 Subject: [PATCH] The Clojure version is now more functional, no mutable state (and without any stack overflows). --- prime.clj/src/prime/clj.clj | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/prime.clj/src/prime/clj.clj b/prime.clj/src/prime/clj.clj index 50ccf66..6fe6c1f 100644 --- a/prime.clj/src/prime/clj.clj +++ b/prime.clj/src/prime/clj.clj @@ -10,12 +10,17 @@ (fn [y] (not= (mod x y) 0)) (range 2 (math/ceil (math/sqrt x)))))) +(defn primes-iter [n, i, v] + (loop [cnt i acc v] + (if (= (count acc) n) acc + (recur (inc cnt) (if (prime? cnt) (conj acc cnt) acc))))) + +(defn primes [n] + (if + (zero? n) [] + (primes-iter n 0 []))) + (defn -main [& args] - (def v []) - (def i 0) - (while (< (count v) (Integer/parseInt (first args))) - (cond (prime? i) (def v (conj v i))) - (def i (inc i))) - (println v)) + (println (primes (Integer/parseInt (first args))))) -- GitLab