Skip to content

Instantly share code, notes, and snippets.

@mourjo
Created January 15, 2022 12:21
Show Gist options
  • Save mourjo/955d02e5edd60a780db669f38731ee7d to your computer and use it in GitHub Desktop.
Save mourjo/955d02e5edd60a780db669f38731ee7d to your computer and use it in GitHub Desktop.
Clojure - Lazy vs non lazy sequence of primes
(defn prime?
[x]
(not-any? (fn [factor] (zero? (mod x factor)))
(range 2 (dec x))))
(defn eager-primes
([n] (eager-primes n 2 []))
([n curr xs]
(if (= n (count xs))
xs
(if (prime? curr)
(recur n (inc curr) (conj xs curr))
(recur n (inc curr) xs)))))
(defn primes
([]
(primes 1))
([curr]
(if (prime? (inc curr))
(lazy-seq (cons (inc curr) (primes (inc curr))))
(lazy-seq (primes (inc curr))))))
@mourjo
Copy link
Author

mourjo commented Jan 15, 2022

;; quel.core>
;; (eager-primes 10)
;; [2 3 5 7 11 13 17 19 23 29]
;; quel.core>
;; (take 10 (primes))
;; (2 3 5 7 11 13 17 19 23 29)
;; quel.core>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment