I found the following text in this doc
[Continuation Passing Style (CPS)] is a programming style where no function is ever allowed to return. A function "A" must emulate returning by passing its would-be-return value to a continuation function that was passed into "A" as an explicit parameter. Thus, all function calls are tail calls, which means, all function calls are instances of "goto with parameters."
What follows is my interpretation. Given the example program:
sub input { ...; return $value; }
sub process1 { my ($input ) = @_; ...; return $result; }
sub process2 { my ($input ) = @_; ...; return $result; }
sub output { my ($result) = @_; ...; }
output(
process1(
process2(
input()
)
)
);
Continuation style, it would look like:
sub input { my ( $c) = @_; ...; &$c($value ); }
sub process1 { my ($input, $c) = @_; ...; &$c($result); }
sub process2 { my ($input, $c) = @_; ...; &$c($result); }
sub output { my ($result ) = @_; ...; }
input(
sub { process1(@_,
sub { process2(@_,
\&output
) }
) }
);
Why oh why? A language and/or compiler designed to optimize function calls at the end of a sub into a goto would compile the above snippet into:
sub input { my ( $c) = @_; ...; @_ = ($value ); goto(&$c); }
sub process1 { my ($input, $c) = @_; ...; @_ = ($result); goto(&$c); }
sub process2 { my ($input, $c) = @_; ...; @_ = ($result); goto(&$c); }
sub output { my ($result ) = @_; ...; }
input(
sub { process1(@_,
sub { process2(@_,
\&output
) }
) }
);
Update: It might even optimize it to the following. I'm deep into speculative waters, now.
goto line1;
input: { my ( $c) = @_; ...; @_ = ($value ); goto($c); }
process1: { my ($input, $c) = @_; ...; @_ = ($result); goto($c); }
process2: { my ($input, $c) = @_; ...; @_ = ($result); goto($c); }
output: { my ($result ) = @_; ...; }
line1: { push(@_, 'line2'); goto input; }
line2: { push(@_, 'line3'); goto process1; }
line3: { push(@_, 'line4'); goto process2; }
line4: { goto output; }
Any why is that good? And what about loops and everything? I'm not exactly sure. And all that being said, I don't know how it relates to coroutines. But it was interesting to me, and I hope it helps you.
|