Advertisement
Guest User

Haskell cooperative multithreading monad

a guest
Feb 20th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Thread (Result(Continue, Yield, Abort), ThreadStatus (..), Thread, funcToThread, runThread) where
  2. import Control.Applicative (Applicative(pure, (<*>)))
  3. import Control.Monad       (liftM, ap)
  4.  
  5. data Result a b c = Continue (c, b) | Yield (c, b) | Resume (b, Thread a b c) | Abort a
  6. newtype Thread a b c = IW (b -> Result a b c)
  7.  
  8. data ThreadStatus a b c = Suspended b (Thread a b c) | Finished b c | Failed a
  9.  
  10. instance Functor (Thread a b) where
  11.     fmap = liftM
  12.  
  13. instance Applicative (Thread a b) where
  14.     pure  = return
  15.     (<*>) = ap
  16.    
  17.  
  18. -- |A monad for cooperative multithreading.
  19. instance Monad (Thread a b) where
  20.   before >>= after = combine before after
  21.   return value = IW (\world -> Continue (value, world))
  22.  
  23. combine :: (Thread a b c) -> (c -> (Thread a b d)) -> (Thread a b d)
  24. combine (IW before) after =
  25.   IW (\input -> case before input of
  26.                   Continue (result, state) -> let IW next = after result
  27.                                               in next state
  28.                   Yield (result, state) ->    let next = after result
  29.                                               in Resume (state, next)
  30.                   Abort message -> Abort message
  31.                   Resume (state, func) -> Resume (state, func >>= after))
  32.  
  33.  
  34. runThread :: Thread a b c -> b -> ThreadStatus a b c
  35. runThread (IW thread) state = case thread state of
  36.                                 Resume (res, next) -> Suspended res next
  37.                                 Abort message -> Failed message
  38.                                 Continue (res, fstat) -> Finished fstat res
  39.                                 Yield (res, fstat) -> Finished fstat res
  40.  
  41.                              
  42. funcToThread :: (b -> Result a b c) -> Thread a b c
  43. funcToThread func = IW func
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement