[ create a new paste ] login | about

Link: http://codepad.org/GwtS6wMj    [ raw code | output | fork ]

haskell - Haskell, pasted on Sep 13:
-- 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


Output:
1
2
3
4
5
1
2
3
13
113


Create a new paste based on this one


Comments: