{-# OPTIONS -Wall #-}
module FilinskiConc where
data ResT m a = Done a | Susp (m (ResT m a))
instance Monad m => Monad (ResT m) where
return = Done
(Done v) >>= f = f v
(Susp r) >>= f = Susp (r >>= \k -> return (k >>= f))
step :: Monad m => m a -> ResT m a
step x = Susp $ x >>= (return . Done)
yield :: Monad m => ResT m ()
yield = Susp (return (return ()))
pOr :: Monad m => ResT m Bool -> ResT m Bool -> ResT m Bool
pOr (Done True) _ = Done True
pOr (Done False) p = p
pOr (Susp t1) t2 = Susp $ t1 >>= \r -> return (pOr t2 r)
atomically :: Monad m => ResT m a -> ResT m a
atomically = work `flip` False where
work (Done a) False = step (return a)
work (Done a) True = Done a
work (Susp t) _ = do { a <- step t ; work a True }
-- Unlike Filinkski's 'par' the 'par' here has a deterministic
-- scheduler - we do one step of a and one step of b at each
-- turn.
--
par :: Monad m => ResT m a -> ResT m b -> ResT m (a,b)
par (Done a) (Done b) = Done (a,b)
par (Done a) (Susp tb) = Susp $ tb >>= \r -> return (r >>= \b -> Done (a,b))
par (Susp ta) (Done b) = Susp $ ta >>= \r -> return (r >>= \a -> Done (a,b))
par (Susp ta) (Susp tb) = do { a <- step ta; b <- step tb; par a b }
run :: Monad m => ResT m a -> m a
run (Susp phi) = phi >>= run
run (Done v) = return v
demo1 :: IO ((),())
demo1 = run (par (step $ putStrLn "a") (step $ putStrLn "b"))
demo2 :: IO Bool
demo2 = run (pOr (step $ do { putStrLn "a"; return False} )
(step $ do { putStrLn "b"; return True} ))
asteps, bsteps :: ResT IO [()]
asteps = mapM (step . putChar) "aaaaaaa"
bsteps = mapM (step . putChar) "bbbbb"
demo3 :: IO ([()],[()])
demo3 = run (par asteps bsteps)
Thursday, January 7, 2010
resumptions
More resumptions, here's a translation of the code from Andrzej Filinski's 'Representing Layered Monads'. I think the translation is accurate, except par in the version below has deterministic scheduling:
Blog Archive
-
▼
2010
(890)
-
▼
January
(48)
- Mullein M2
- KURE
- Mullein M2
- data-aviary
- arity-lib
- Mullein M2
- Hurdle and Kangaroo
- kangaroo
- kangaroo
- SFont - ZFont
- Hurdle, SFont and Kangaroo
- kangaroo
- kangaroo
- kangaroo
- kangaroo
- kangaroo
- kangaroo
- data-aviary
- data-aviary
- OpenVG binding
- OpenVG binding
- OpenVG binding
- OpenVG binding
- OpenVG binding
- precis
- precis
- precis
- precis
- precis
- precis
- zparse
- zparse
- zparse
- zparse
- zparse
- zparse
- zparse
- resumptions
- resumptions
- kangaroo
- kangaroo
- Hurdle and kangaroo
- kangaroo
- kangaroo
- kangaroo
- kangaroo
- kangaroo
- kangaroo
-
▼
January
(48)
About Me
- Stephen Tetley
- Disambiguating biog as there are a few Stephen Tetley's in the world. I'm neither a cage fighter or yachtsman. I studied Fine Art in the nineties (foundation Bradford 1992, degree Cheltenham 1992 - 95) then Computing part-time at Leeds Met graduating in 2003. I'm the Stephen Tetley on Haskell Cafe and Stackoverflow.