drama-0.3.0.0: Actor library for Haskell
Copyright© 2021 Evan Relf
LicenseBSD-3-Clause
Maintainerevan@evanrelf.com
Stabilityexperimental
Safe HaskellSafe-Inferred
LanguageHaskell2010

Drama.Loop

Contents

Description

 
Synopsis

Documentation

loop Source #

Arguments

:: Monad m 
=> s

Initial state

-> (s -> m (Either s a))

Action to perform, returning either a new state to continue looping, or a final value to stop looping.

-> m a 

Loop indefinitely with state. Use forever for stateless infinite loops.

Example
Expand
counter :: Process NoMsg ()
counter = loop (10 :: Int) \count -> do
  liftIO $ print count
  if count > 0
    then continue (count - 1)
    else exit ()

Since: 0.3.0.0

continue :: Monad m => s -> m (Either s a) Source #

Continue looping with some new state.

continue s = pure (Left s)

Since: 0.3.0.0

stop :: Monad m => a -> m (Either s a) Source #

Stop looping and return with a final value.

exit x = pure (Right x)

Since: 0.3.0.0

Re-exports

forever :: Applicative f => f a -> f b #

Repeat an action indefinitely.

Using ApplicativeDo: 'forever as' can be understood as the pseudo-do expression

do as
   as
   ..

with as repeating.

Examples

Expand

A common use of forever is to process input from network sockets, Handles, and channels (e.g. MVar and Chan).

For example, here is how we might implement an echo server, using forever both to listen for client connections on a network socket and to echo client input on client connection handles:

echoServer :: Socket -> IO ()
echoServer socket = forever $ do
  client <- accept socket
  forkFinally (echo client) (\_ -> hClose client)
  where
    echo :: Handle -> IO ()
    echo client = forever $
      hGetLine client >>= hPutStrLn client