forked from ikhoon/FP101x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter11-lab5.hs
97 lines (66 loc) · 2.2 KB
/
chapter11-lab5.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
module Lab5 where
import Control.Monad
data Concurrent a = Concurrent ((a -> Action) -> Action)
data Action
= Atom (IO Action)
| Fork Action Action
| Stop
instance Show Action where
show (Atom x) = "atom"
show (Fork x y) = "fork " ++ show x ++ " " ++ show y
show Stop = "stop"
-- ===================================
-- Ex. 0
-- ===================================
action :: Concurrent a -> Action
action = error "You have to implement action"
-- ===================================
-- Ex. 1
-- ===================================
stop :: Concurrent a
stop = error "You have to implement stop"
-- ===================================
-- Ex. 2
-- ===================================
atom :: IO a -> Concurrent a
atom = error "You have to implement atom"
-- ===================================
-- Ex. 3
-- ===================================
fork :: Concurrent a -> Concurrent ()
fork = error "You have to implement fork"
par :: Concurrent a -> Concurrent a -> Concurrent a
par = error "You have to implement par"
-- ===================================
-- Ex. 4
-- ===================================
instance Monad Concurrent where
(Concurrent f) >>= g = error "test"
return x = Concurrent (\c -> c x)
-- ===================================
-- Ex. 5
-- ===================================
roundRobin :: [Action] -> IO ()
roundRobin = error "You have to implement roundRobin"
-- ===================================
-- Tests
-- ===================================
ex0 :: Concurrent ()
ex0 = par (loop (genRandom 1337)) (loop (genRandom 2600) >> atom (putStrLn ""))
ex1 :: Concurrent ()
ex1 = do atom (putStr "Haskell")
fork (loop $ genRandom 7331)
loop $ genRandom 42
atom (putStrLn "")
-- ===================================
-- Helper Functions
-- ===================================
run :: Concurrent a -> IO ()
run x = roundRobin [action x]
genRandom :: Int -> [Int]
genRandom 1337 = [1, 96, 36, 11, 42, 47, 9, 1, 62, 73]
genRandom 7331 = [17, 73, 92, 36, 22, 72, 19, 35, 6, 74]
genRandom 2600 = [83, 98, 35, 84, 44, 61, 54, 35, 83, 9]
genRandom 42 = [71, 71, 17, 14, 16, 91, 18, 71, 58, 75]
loop :: [Int] -> Concurrent ()
loop xs = mapM_ (atom . putStr . show) xs