-- Coroutines
-- from ddarius.
module Main () where
import Control.Concurrent
import Control.Concurrent.MVar
coroutine thr = do
send <- newEmptyMVar
recv <- newEmptyMVar
forkIO (takeMVar recv >>=
thr (\x -> putMVar send x >> takeMVar recv) >>=
putMVar send)
return (\x -> putMVar recv x >> takeMVar send)
step yield n | n > 100 = return n
| otherwise = yield n >>= step yield . (n+)
main = do
callstep <- coroutine step
print =<< callstep 1
print =<< callstep 1
print =<< callstep 1
print =<< callstep 10
print =<< callstep 100
-- print =<< callstep 39 -- would block