Skip to content

Commit

Permalink
Use Data.Set (\\) and additional implementation using just Data.List
Browse files Browse the repository at this point in the history
  • Loading branch information
steshaw committed Jan 14, 2015
1 parent f9a41fe commit 9ac94ae
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions haskell/yorgey-lectures/week-04/Primes.hs
Expand Up @@ -5,20 +5,33 @@ infixl 0 |>
-}

import qualified Data.Set as S
import Data.List

cartProd :: [a] -> [b] -> [(a, b)]
cartProd xs ys = [(x, y) | x <- xs, y <- ys]

sieveSundaram :: Integer -> [Integer]
sieveSundaram n = map twiddle . filter notInUnprimes $ nums
sieveSundaram n = map twiddle . S.toList $ setNums S.\\ unprimes
where
nums :: [Integer]
nums = [1..n]
setNums :: S.Set Integer
setNums = S.fromList nums
twiddle :: Integer -> Integer
twiddle m = m * 2 + 1
notInUnprimes :: Integer -> Bool
notInUnprimes e = S.notMember e unprimes
unprimes :: S.Set Integer
unprimes = S.fromList . takeWhile (<= n) . map f . filter (uncurry (<=)) $ cartProd nums nums
where
f (i, j) = i + j + (2 * i * j)

sieveSundaram1 :: Integer -> [Integer]
sieveSundaram1 n = map twiddle $ nums \\ unprimes
where
nums :: [Integer]
nums = [1..n]
twiddle :: Integer -> Integer
twiddle m = m * 2 + 1
unprimes :: [Integer]
unprimes = takeWhile (<= n) . map f . filter (uncurry (<=)) $ cartProd nums nums
where
f (i, j) = i + j + (2 * i * j)

0 comments on commit 9ac94ae

Please sign in to comment.