Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I personally think the priority queue one is somewhat simpler than a fixed array algorithm. It also produces an infinite list of primes (or generator) instead of the primes up to a particular number. This is especially important in Haskell.

I'd love to see it as it shows off some great data structures available in the libraries (like priority queues) but it's getting longish.

The mutable array version is basically the same as imperative code everywhere

    sieveUA :: Int -> UArray Int Bool
    sieveUA top = runSTUArray $ do
        let m = (top-1) `div` 2
            r = floor . sqrt $ fromIntegral top + 1
        sieve <- newArray (1,m) True
        forM_ [1..r `div` 2] $ \i -> do
          isPrime <- readArray sieve i
          when isPrime $ do
            forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do
              writeArray sieve j False
        return sieve
It's a bit noisy syntactically and doesn't show off as much interesting stuff.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: