After reading Dan's recent blog entry, I realized how (semantically)
ugly coroutines are, with all the different ways of calling them, and
dealing with parameters, etc.
There's a couple problems as far as what's easy with the approaches
described there. For instance, you can't really have a coroutine that
everyone can call with the same state, because it would either start
over, or create a new one.
It's very hard to maintain several coroutine states of the same
coroutine in the same scope. You have to do tricky stuff with
closures, or some other such workaround.
So, since they are generally used as iterators, why not steal the
iterator semantics for them? This clears up most of the issues:
sub range($start, $end) is coroutine {
for $start .. $end { yield $_ }
}
my $iter = range(1,10); # Doesn't actually run range's code.
for <$iter> {
print "Got $_"
}
So calling a function declared as a coroutine wouldn't run anything at
all. It would return an iterator, that when advanced would run until
the first C<yield>.
A problem that I see is that this breaks the "encapsulation" of
continuing a coroutine being equivalent to just calling a function.
However, coroutines are stateful, so it should be explicit that you're
using an existing state rather than starting a new one (as in the case
of a function call).
Luke
Thread Next