Created
March 26, 2014 13:35
-
-
Save valyakuttan/9783256 to your computer and use it in GitHub Desktop.
Brief intro to ST monad http://stackoverflow.com/questions/8197032/starray-documentation-for-newbies-and-state-st-related-questions
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
import Control.Monad | |
import Control.Monad.ST | |
import Data.Array.ST | |
import Data.Array.Unboxed | |
primesUpto :: Int -> [Int] | |
primesUpto n = [p | (p, True) <- assocs $ sieve n] | |
sieve :: Int -> UArray Int Bool | |
sieve n = runSTUArray $ do | |
sieve <- newArray (2, n) True | |
forM_ [2..n] $ \p -> do | |
isPrime <- readArray sieve p | |
when isPrime $ do | |
forM_ [p*2, p*3 .. n] $ \k -> do | |
writeArray sieve k False | |
return sieve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment