This and other RFCs are available on the web at
  http://tmtowtdi.perl.org/rfc/

=head1 TITLE

Co-routines

=head1 VERSION

  Maintainer: Damian Conway <[EMAIL PROTECTED]>
  Date: 4 August 2000
  Version: 1.00
  Mailing List: [EMAIL PROTECTED]
  Number: 31

=head1 ABSTRACT

This RFC proposes the addition of a new function return command:
C<yield>. Unlike C<return>, C<yield> preserves the execution state of
the subroutine in which it's called, allowing the execution to be
resumed at the following statement, next time the subroutine is called.
It is also proposed that C<yields> may nest, to simplify the
construction of recursive co-routines and iterators.

=head1 BACKGROUND

Normally, when a subroutine returns, its execution terminates
and it final context is completely lost. The next time the subroutine
is invoked, it recommences executing from its first statement.

In a coroutine, a value may be returned in such a way that the 
execution of the routine is I<suspended>, along with all its 
local context. The next time the routine in invoked, its execution
resumes from the statement after the previous point of return.

=head1 DESCRIPTION

It is proposed to add a new control statement to Perl: C<yield>.
A C<yield> acts very much like a C<return> in that it terminates
execution of the enclosing subroutine and returns a value to its calling
context. However, when a value is C<yield>'ed, the subroutine's execution
is suspended in such a way that it resumes from the following statement
next time the subroutine is invoked. 

Note that any subroutine containing a C<yield> is implicitly a co-routine.
There is no explicit keyword or attribute proposed.

Coroutines make it very easy to implement generic parameteric closures
and iterators:

        package Tree;

        sub next_inorder ($self) {
                yield $self->{left}->next_inorder if $self->{left};
                yield $self;
                yield $self->{right}->next_inorder if $self->{right};
                return undef;
        }


        # and later...

                while (my $node = $root->next_inorder()) {
                        print $node->{data};
                }


Note that the above example implies (correctly) that yielding a result
which itself was yielded leaves the suspended execution of the
subroutine at the same C<yield> statement (I<not> the following
statement). Furthermore, yielding an C<undef> is a no-op (i.e. it
doesn't cause the subroutine to return, but passes control to the next
statement).

Note that the arguments of a co-routine are ignored when it is resumed.
Hence:

        sub every_second ( @vals ) {
                yield (splice @vals, 0, 2)[0]  while @vals;
                return;
        }


=head1 IMPLEMENTATION

Tricky.

Reply via email to