module Simulation.Aivika.GPSS.Block.Terminate
(terminateBlock,
terminateBlockByCount,
terminateBlockByCountM) where
import Control.Monad
import Control.Monad.Trans
import Simulation.Aivika
import Simulation.Aivika.GPSS.Block
terminateBlock :: Block a ()
terminateBlock :: forall a. Block a ()
terminateBlock =
Block { blockProcess :: a -> Process ()
blockProcess = \a
a -> forall (m :: * -> *) a. Monad m => a -> m a
return () }
terminateBlockByCountM :: Ref Int
-> Event Int
-> Block a ()
terminateBlockByCountM :: forall a. Ref Int -> Event Int -> Block a ()
terminateBlockByCountM Ref Int
counter Event Int
decrement =
Block { blockProcess :: a -> Process ()
blockProcess = \a
a -> Process ()
action }
where
action :: Process ()
action =
forall (m :: * -> *) a. EventLift m => Event a -> m a
liftEvent forall a b. (a -> b) -> a -> b
$
do Int
i <- Event Int
decrement
Int
n <- forall a. Ref a -> Event a
readRef Ref Int
counter
let n' :: Int
n' = Int
n forall a. Num a => a -> a -> a
- Int
i
Int
n' seq :: forall a b. a -> b -> b
`seq` forall a. Ref a -> a -> Event ()
writeRef Ref Int
counter Int
n'
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
n' forall a. Ord a => a -> a -> Bool
<= Int
0) forall a b. (a -> b) -> a -> b
$
forall e a. Exception e => e -> Event a
throwEvent forall a b. (a -> b) -> a -> b
$
String -> SimulationAbort
SimulationAbort String
"Terminated by exceeding the counter"
terminateBlockByCount :: Ref Int
-> Int
-> Block a ()
terminateBlockByCount :: forall a. Ref Int -> Int -> Block a ()
terminateBlockByCount Ref Int
counter Int
i =
Block { blockProcess :: a -> Process ()
blockProcess = \a
a -> Process ()
action }
where
action :: Process ()
action =
forall (m :: * -> *) a. EventLift m => Event a -> m a
liftEvent forall a b. (a -> b) -> a -> b
$
do Int
n <- forall a. Ref a -> Event a
readRef Ref Int
counter
let n' :: Int
n' = Int
n forall a. Num a => a -> a -> a
- Int
i
Int
n' seq :: forall a b. a -> b -> b
`seq` forall a. Ref a -> a -> Event ()
writeRef Ref Int
counter Int
n'
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
n' forall a. Ord a => a -> a -> Bool
<= Int
0) forall a b. (a -> b) -> a -> b
$
forall e a. Exception e => e -> Event a
throwEvent forall a b. (a -> b) -> a -> b
$
String -> SimulationAbort
SimulationAbort String
"Terminated by exceeding the counter"