No title

Anonymous Coward 2018-03-12 21:52:07.695153 UTC

1{-# LANGUAGE KindSignatures #-}
2{-# LANGUAGE RecordWildCards #-}
3module Monad.Types where
4
5import Data.Function.Unicode
6import Data.Hashable
7import Data.HashMap
8import Data.IORef
9
10
11data Access = ARead | AWrite
12
13-- An abstraction over a key-value store implementing a shared state
14-- with concurrent support for one writer and many readers.
15class SharedState (s Access * * *) where
16 new IO (s AWrite k v)
17 write (Hashable k, Ord k) k v s AWrite k v IO ()
18 read (Hashable k, Ord k) k s a k v IO (Maybe v)
19 size (Hashable k, Ord k) s a k v IO Int
20 writeMany (Hashable k, Ord k) [(k, v)] s AWrite k v IO ()
21 writeMany kvs m = mapM_ (\(k, v) write k v m) kvs
22
23
24data IORefHashMap (a Access) k v = IORefHashMap (IORef (Map k v))
25
26instance SharedState IORefHashMap where
27 new = IORefHashMap <$> newIORef empty
28 read k (IORefHashMap m) = readIORef m >>= return ∘ lookup k
29 write k v (IORefHashMap m) = modifyIORef' m (insert k v)
30 size (IORefHashMap m) = readIORef m >>= return ∘ Data.HashMap.size