| 51 | | This function takes two coroutines as arguments, producer and consumer. The producer gets a sink argument, and the consumer a source argument. All data that the producer writes to the sink can be read from the source by the consumer. This arrangement couldn't be simpler. |
| | 51 | This function takes two coroutines as arguments, ''producer'' and ''consumer''. The producer gets a sink argument, and the consumer a source argument. All data that the producer writes to the sink can be read from the source by the consumer. The arrangement couldn't be simpler. Here is a contrived example of a producer/consumer pair: |
| | 52 | |
| | 53 | {{{ |
| | 54 | import Control.Concurrent.Coroutine |
| | 55 | import Control.Concurrent.SCC.Streams |
| | 56 | |
| | 57 | main = runCoroutine (pipe (rangeProducer 1 10) (sumConsumer 0)) >>= print |
| | 58 | |
| | 59 | rangeProducer min max sink | min > max = return () |
| | 60 | | otherwise = put sink min |
| | 61 | >> rangeProducer (succ min) max sink |
| | 62 | sumConsumer sum source = get source |
| | 63 | >>= maybe (return sum) |
| | 64 | (\n-> sumConsumer (sum + n) source) |
| | 65 | }}} |
| | 66 | |
| | 67 | The {{{rangeProducer}}} coroutine produces a range of integers while the {{{sumConsumer}}} consumes all the numbers and sums them up. The two coroutines are bound together by {{{pipe}}}. Note that either of them could be bound to a different coroutine and still perform its job. Furthermore, though in this example both coroutines run in the IO monad, they are completely generic and could run in any monad. |