I'm currently learning Clojure and am stuck with list comprehension.
;; https://stackoverflow.com/a/7625207/4110233
(defn gen-primes "Generates an infinite, lazy sequence of prime numbers"
[]
(letfn [(reinsert [table x prime]
(update-in table [(+ prime x)] conj prime))
(primes-step [table d]
(if-let [factors (get table d)]
(recur (reduce #(reinsert %1 d %2) (dissoc table d) factors)
(inc d))
(lazy-seq (cons d (primes-step (assoc table (* d d) (list d))
(inc d))))))]
(primes-step {} 2)))
(defn prime-factors-not-working [x]
(for [y (gen-primes)
:when (= (mod x y) 0)
:while (< y (Math/sqrt x))]
y))
(defn prime-factors-working [x]
(for [y (gen-primes)
:while (< y (Math/sqrt x))
:when (= (mod x y) 0)]
y))
(prime-factors-working 100)
;; ↪ (2 5)
(prime-factors-not-working 100)
;; Goes into infinite loop
(gen-primes)
is a lazy sequence of prime numbers. The only difference between the working and not-working sequences is the order of the modifiers while
and when
. Why does the not-working
implementation go into an infinite loop?