|
|
A while back, I asked a question on Stack Overflow. Monads let you do a
lot of trippy things, like writing multi-valued functions and simulating
non-deterministic execution, or writing mutable code which is guaranteed
to produce a pure result, and so on. But using the responses from SO, I
was able to implement a monad that does something even more surprising:
You can write code which is /pausable/.
Writing some code which does something is pretty easy. (E.g., imagine
trying to write a Huffman encoder.) Writing some code which SHOWS you
what it's doing is much harder. Typically the actual logic that does the
interesting stuff gets buried amongst the code to update the display,
and to keep track of the current state so you can resume processing on
the next step.
By writing some surprisingly straight-forward code, I was able to create
a special monad that supports /pausing/ the code running within it.
Normally, you write a monad, and then write a "run" function which
executes the code written in the monad and hands you the end result. But
with the pause monad, there is a special "yield" command which causes
control to pass back to the caller.
By this arrangement, you can write your code as if you /aren't/ trying
to display progress interactively, except that after each logical
"step", you insert a yield command. The caller then runs each step, and
updates the display to show what just happened.
Gee, I think...... I think I just reinvented coroutines! o_O
That's what a coroutine is, right? A pair of code blocks that invoke
each other?
Post a reply to this message
|
|