Created
July 20, 2013 03:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
my-and
is hacky. I had to do that becauseand
is a macro, not a function. Looking back, I kind of like this way of definingall?
:And it's faster because unlike reducing with
my-and
, this will short circuit. I still think it's silly that thisall?
function isn't built in.Another hacky thing is adding 0.1 to the square root passed to
range
. I did this becauserange
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