Skip to content

Instantly share code, notes, and snippets.

@graue
Created July 20, 2013 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graue/6043792 to your computer and use it in GitHub Desktop.
Save graue/6043792 to your computer and use it in GitHub Desktop.
Lazy list of primes, as implemented in 15 minutes on the subway on my phone
(defn divides [m n]
(= 0
(mod n m)))
(defn my-and [x y]
(and x y))
(defn all? [pred xs]
(reduce my-and true
(map pred xs)))
(defn prime? [n]
(and
(not (== n 1))
(not (== n 0))
(all?
#(not (divides % n))
(range 2 (+ 0.1 (Math/sqrt n))))))
(def primes
(filter prime?
(range)))
@graue
Copy link
Author

graue commented Jul 20, 2013

my-and is hacky. I had to do that because and is a macro, not a function. Looking back, I kind of like this way of defining all?:

(defn all? [pred xs]
  (not (some #(not (pred %)) xs)))

And it's faster because unlike reducing with my-and, this will short circuit. I still think it's silly that this all? function isn't built in.

Another hacky thing is adding 0.1 to the square root passed to range. I did this because range excludes the stop value. If I don't add anything to the sqrt, perfect squares like (prime? 9) incorrectly become true. If I add 1, then 2 is incorrectly reported as not prime. A more elegant way would be to use

(range 2 (Math/ceil (Math/sqrt n)))

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