-- |
-- Module     : Simulation.Aivika.GPSS.Block.Loop
-- Copyright  : Copyright (c) 2017, David Sorokin <david.sorokin@gmail.com>
-- License    : BSD3
-- Maintainer : David Sorokin <david.sorokin@gmail.com>
-- Stability  : experimental
-- Tested with: GHC 8.0.2
--
-- This module defines the GPSS block LOOP.
--
module Simulation.Aivika.GPSS.Block.Loop
       (loopBlock,
        loopBlockM) where

import Simulation.Aivika
import Simulation.Aivika.GPSS.Block

-- | This is the GPSS construct
--
-- @LOOP A,B@
loopBlock :: (a -> (b, Bool))
             -- ^ by the specified transact return the next version
             -- of the same transact and a condition whether we should
             -- exit the loop
             -> Block b ()
             -- ^ the block to transfer in when the condition fails
             -> Block a b
loopBlock :: (a -> (b, Bool)) -> Block b () -> Block a b
loopBlock a -> (b, Bool)
f Block b ()
block =
  Block :: forall a b. (a -> Process b) -> Block a b
Block { blockProcess :: a -> Process b
blockProcess = \a
a ->
           do let (b
b, Bool
c) = a -> (b, Bool)
f a
a
              if Bool
c
                then b -> Process b
forall (m :: * -> *) a. Monad m => a -> m a
return b
b
                else Process () -> Process b
forall a. Process () -> Process a
transferProcess (Block b () -> b -> Process ()
forall a b. Block a b -> a -> Process b
blockProcess Block b ()
block b
b)
        }

-- | This is the GPSS construct
--
-- @LOOP A,B@
loopBlockM :: (a -> Process (b, Bool))
              -- ^ by the specified transact return the next version
              -- of the same transact and a condition whether we should
              -- exit the loop
              -> Block b ()
              -- ^ the block to transfer in when the condition fails
              -> Block a b
loopBlockM :: (a -> Process (b, Bool)) -> Block b () -> Block a b
loopBlockM a -> Process (b, Bool)
f Block b ()
block =
  Block :: forall a b. (a -> Process b) -> Block a b
Block { blockProcess :: a -> Process b
blockProcess = \a
a ->
           do (b
b, Bool
c) <- a -> Process (b, Bool)
f a
a
              if Bool
c
                then b -> Process b
forall (m :: * -> *) a. Monad m => a -> m a
return b
b
                else Process () -> Process b
forall a. Process () -> Process a
transferProcess (Block b () -> b -> Process ()
forall a b. Block a b -> a -> Process b
blockProcess Block b ()
block b
b)
        }