Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Thread (Result(Continue, Yield, Abort), ThreadStatus (..), Thread, funcToThread, runThread) where
- import Control.Applicative (Applicative(pure, (<*>)))
- import Control.Monad (liftM, ap)
- data Result a b c = Continue (c, b) | Yield (c, b) | Resume (b, Thread a b c) | Abort a
- newtype Thread a b c = IW (b -> Result a b c)
- data ThreadStatus a b c = Suspended b (Thread a b c) | Finished b c | Failed a
- instance Functor (Thread a b) where
- fmap = liftM
- instance Applicative (Thread a b) where
- pure = return
- (<*>) = ap
- -- |A monad for cooperative multithreading.
- instance Monad (Thread a b) where
- before >>= after = combine before after
- return value = IW (\world -> Continue (value, world))
- combine :: (Thread a b c) -> (c -> (Thread a b d)) -> (Thread a b d)
- combine (IW before) after =
- IW (\input -> case before input of
- Continue (result, state) -> let IW next = after result
- in next state
- Yield (result, state) -> let next = after result
- in Resume (state, next)
- Abort message -> Abort message
- Resume (state, func) -> Resume (state, func >>= after))
- runThread :: Thread a b c -> b -> ThreadStatus a b c
- runThread (IW thread) state = case thread state of
- Resume (res, next) -> Suspended res next
- Abort message -> Failed message
- Continue (res, fstat) -> Finished fstat res
- Yield (res, fstat) -> Finished fstat res
- funcToThread :: (b -> Result a b c) -> Thread a b c
- funcToThread func = IW func
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement