Operational Semantics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}

-- Pasted from: http://www.haskell.org/haskellwiki/Prime_numbers

module Primes (nthPrime) where
 
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Base
import System
import Control.Monad
import Data.Bits
 
nthPrime :: Int -> Int
nthPrime n = runST (sieve n)
 
sieve n = do
    a <- newArray (3,n) True :: ST s (STUArray s Int Bool)
    let cutoff = truncate (sqrt $ fromIntegral n) + 1
    go a n cutoff 3 1
 
go !a !m cutoff !n !c
    | n >= m    = return c
    | otherwise = do
        e <- unsafeRead a n
        if e then
            if n < cutoff then
                let loop !j
                        | j < m     = do
                            x <- unsafeRead a j
                            when x $ unsafeWrite a j False
                            loop (j+n)
                        | otherwise = go a m cutoff (n+2) (c+1)
                in loop ( if n < 46340 then n * n else n `shiftL` 1)
             else go a m cutoff (n+2) (c+1)
         else go a m cutoff (n+2) c

-- My Functions:
const' = \a _ -> a

test1 c = let a = const' (nthPrime 100000)
          in (a c, a c)

test2 c = let a = \_ -> (nthPrime 100000)
          in (a c, a c)