2 ms·
Coroutines fit into some functional languages fairly naturally. They can be constructed out of the primitive operator call/cc (call with current continuation)
by retrac 5y ago
Coroutines fit into some functional languages fairly naturally. They can be constructed out of the primitive operator call/cc (call with current continuation) in Scheme and simple cooperative threading, exceptions, callbacks, coroutines, etc. are usually implemented that way in Scheme, and pretty widely used. It meshes okay I guess with the rest of the language and libraries, but Scheme doesn't really have much in the way of libraries.
Coroutines are a type of monad in Haskell. If you want function calls to alternate between execution streams, that sort of chaining of execution, is what Haskell's monads deal with. Instance the type you're using in the Coroutine class, and any functions with the same Coroutine type, will automatically work as coroutines between each other when you suspend them. It's part of the standard library in Control.Monad.Coroutine. Since it's a monad, it composes with other monads, and will work with most library code. As to IO, with a lazy evaluation language, when a blocking call is made, other parts that can still evaluate (not just pending coroutines but also regular functions not depending on the blocking call) can continue, so all IO in Haskell sort of works as you describe there, I think. Lazy evaluation is usually implemented with coroutines, IIRC. In a sense, every value in the program is in its own coroutine, that runs when the value needs to be calculated because some other value depends on it. Analyzing the efficiency of lazy programs suffers the same kind of problem you mention with concurrent programs, to be fair.