User:Duplode/Contrived ST example
Appearance
import Control.Monad.ST
import Data.STRef
import Control.Monad
import System.Random
import qualified Data.HashTable.ST.Basic as H
type HashTable k v = H.HashTable k v
type RandomSeed = Int
scatter :: RandomSeed -> (Int, Integer)
scatter seed = runST $ do
gen <- newSTRef $ mkStdGen seed
hsh <- H.new
replicateM_ (1000 * 1000) $ do
gen1 <- readSTRef gen
let (k, gen2) = randomR (0, 1000 * 1000) gen1
(v, gen3) = randomR (0, 1000 * 1000) gen2
H.insert hsh (k :: Int) (v :: Integer)
writeSTRef gen gen3
let lookCountAdd p@(c, s) n = do
mx <- H.lookup hsh n
return $ case mx of
Nothing -> p
Just x -> (c + 1, s + x)
foldM lookCountAdd (0, 0) [1..100 * 1000]