-
Notifications
You must be signed in to change notification settings - Fork 3
/
NServerState.hs
53 lines (43 loc) · 2.12 KB
/
NServerState.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
module NServerState ( NServerState
, naddToQueue
, nserverStep
, nsimulationStep
, nserverStart
, nserverSize
, nshortestQueue ) where
import QueueState ( QueueState
, addMessage
, queueStep
, queueStart
, queueLength
, queueEmpty )
import Chapter_14_my_note ( Inmess (..)
, Outmess (..) )
data NServerState = NSS { index :: Int, threads :: [QueueState] } deriving (Show, Eq)
naddToQueue :: Inmess -> NServerState -> NServerState
naddToQueue wtf nsv@ (NSS ind threadq)
= NSS (if ind + 1 == nserverSize nsv then 0 else ind + 1) (modify wtf ind threadq)
modify :: Inmess -> Int -> [QueueState] -> [QueueState]
modify inms loc thrads
= take loc thrads ++ [addMessage inms (thrads !! loc)] ++ drop (loc + 1) thrads
nserverStep :: NServerState -> (NServerState, [Outmess])
nserverStep (NSS idx []) = (NSS idx [], [])
nserverStep (NSS idx (q : qs)) = (NSS idx (_q : _qs), oms ++ omsl)
where (_q, oms) = queueStep q
(NSS _ _qs, omsl) = nserverStep (NSS idx qs)
nsimulationStep :: NServerState -> Inmess -> (NServerState, [Outmess])
nsimulationStep nsv inm = (naddToQueue inm servModf, omsl)
where (servModf, omsl) = nserverStep nsv
nserverStart :: Int -> NServerState
nserverStart thread_num = NSS 0 (replicate thread_num queueStart)
nserverSize :: NServerState -> Int
nserverSize (NSS _ threadq) = length threadq
nshortestQueue :: NServerState -> Int
nshortestQueue (NSS _ []) = error "no thread"
nshortestQueue (NSS _ [_]) = 0
nshortestQueue (NSS idx (q : qs))
| rstShortestLen <= currQlen = 1 + rstShortest
| otherwise = 0
where currQlen = queueLength q :: Int
rstShortest = nshortestQueue (NSS idx qs) :: Int
rstShortestLen = queueLength (qs !! rstShortest)