Created
May 7, 2010 04:29
-
-
Save trptcolin/393055 to your computer and use it in GitHub Desktop.
This file contains 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
(ns sieve | |
(:use clojure.test)) | |
(defn square [x] (* x x)) | |
(defn seq-contains? [ls x] | |
(boolean (some #{x} ls))) | |
(defn multiple-of? [product divisor] | |
(and (= 0 (mod product divisor)) | |
(not (= product divisor)))) | |
(defn primes-less-than [n] | |
(loop [current-n 2 potential-primes (range 2 n)] | |
(if (> (square current-n) n) | |
potential-primes | |
(if (seq-contains? potential-primes current-n) | |
(recur (inc current-n) (remove #(multiple-of? % current-n) potential-primes)) | |
(recur (inc current-n) potential-primes))))) | |
(is (= () (primes-less-than 2))) | |
(is (= '(2) (primes-less-than 3))) | |
(is (= '(2 3) (primes-less-than 4))) | |
(is (= '(2 3) (primes-less-than 5))) | |
(is (= '(2 3 5) (primes-less-than 6))) | |
(is (= '(2 3 5) (primes-less-than 7))) | |
(is (= '(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47) (primes-less-than 50))) |
Cool, I like that set-as-predicate idiom. Updated to use it. The boolean coercion isn't necessary, you're right, but I feel like a function ending with ? ought to return true or false. It's a trade-off, I guess.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, you can write (some #{x} seq) instead of (some #(= % x) seq).
Nice idiom I've discovered recently - reading docs ;)
Also why do you coerce to boolean in "seq-contains?" ?