forked from simonmar/parconc-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phonebook.hs
42 lines (36 loc) · 920 Bytes
/
phonebook.hs
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
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Concurrent
import Prelude hiding (lookup)
-- <<types
type Name = String
type PhoneNumber = String
type PhoneBook = Map Name PhoneNumber
newtype PhoneBookState = PhoneBookState (MVar PhoneBook)
-- >>
-- <<new
new :: IO PhoneBookState
new = do
m <- newMVar Map.empty
return (PhoneBookState m)
-- >>
-- <<insert
insert :: PhoneBookState -> Name -> PhoneNumber -> IO ()
insert (PhoneBookState m) name number = do
book <- takeMVar m
putMVar m (Map.insert name number book)
-- >>
-- <<lookup
lookup :: PhoneBookState -> Name -> IO (Maybe PhoneNumber)
lookup (PhoneBookState m) name = do
book <- takeMVar m
putMVar m book
return (Map.lookup name book)
-- >>
-- <<main
main = do
s <- new
sequence_ [ insert s ("name" ++ show n) (show n) | n <- [1..10000] ]
lookup s "name999" >>= print
lookup s "unknown" >>= print
-- >>