on 5cbcd5b help sign in
streamly/examples/AcidRain.hs
43 lines 1.4 kB history raw
1{-# LANGUAGE FlexibleContexts #-}
3-- This example is adapted from Gabriel Gonzalez's pipes-concurrency package.
4-- https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html
6import Streamly
7import Streamly.Prelude as S
8import Control.Monad (when)
9import Control.Monad.IO.Class (MonadIO(liftIO))
10import Control.Monad.State (MonadState, get, modify, runStateT, put)
12data Event = Harm Int | Heal Int deriving (Show)
14userAction :: MonadAsync m => SerialT m Event
15userAction = S.repeatM $ liftIO askUser
16 where
17 askUser = do
18 command <- getLine
19 case command of
20 "potion" -> return (Heal 10)
21 "quit" -> fail "quit"
22 _ -> putStrLn "What?" >> askUser
24acidRain :: MonadAsync m => SerialT m Event
25acidRain = asyncly $ constRate 1 $ S.repeatM $ liftIO $ return $ Harm 1
27game :: (MonadAsync m, MonadState Int m) => SerialT m ()
28game = do
29 event <- userAction `parallel` acidRain
30 case event of
31 Harm n -> modify $ \h -> h - n
32 Heal n -> modify $ \h -> h + n
34 h <- get
35 when (h <= 0) $ fail "You die!"
36 liftIO $ putStrLn $ "Health = " <> show h
38main :: IO ()
39main = do
40 putStrLn "Your health is deteriorating due to acid rain,\
41 \ type \"potion\" or \"quit\""
42 _ <- runStateT (runStream game) 60
43 return ()