CPS
view release on metacpan or search on metacpan
#
# (C) Paul Evans, 2008-2010 -- leonerd@leonerd.org.uk
package CPS;
use strict;
use warnings;
our $VERSION = '0.19';
use Carp;
our @CPS_PRIMS = qw(
kloop
kwhile
kforeach
kdescendd kdescendb
kpar
kpareach
kseq
);
our @EXPORT_OK = (
@CPS_PRIMS,
map( "g$_", @CPS_PRIMS ),
qw(
liftk
dropk
),
);
use Exporter 'import';
use CPS::Governor::Simple;
# Don't hard-depend on Sub::Name since it's only a niceness for stack traces
BEGIN {
if( eval { require Sub::Name } ) {
*subname = \&Sub::Name::subname;
}
else {
# Ignore the name, return the CODEref
*subname = sub { return $_[1] };
}
}
=head1 NAME
C<CPS> - manage flow of control in Continuation-Passing Style
=head1 OVERVIEW
=over 4
B<Note>: This module is entirely deprecated now. It is maintained for
compatibility for any code still using it, but please consider rewriting to
use L<Future> instead, which offers a far neater method of representing
asynchronous program and data flow. In addition, L<Future::AsyncAwait> can
further improve readability of C<Future>-based code by letting it use the
familiar kinds of Perl control structure while still being asynchronous.
At some later date this entire C<CPS> module distribution may be deleted.
=back
The functions in this module implement or assist the writing of programs, or
parts of them, in Continuation Passing Style (CPS). Briefly, CPS is a style
of writing code where the normal call/return mechanism is replaced by explicit
"continuations", values passed in to functions which they should invoke, to
implement return behaviour. For more detail on CPS, see the SEE ALSO section.
What this module implements is not in fact true CPS, as Perl does not natively
support the idea of a real continuation (such as is created by a co-routine).
Furthermore, for CPS to be efficient in languages that natively support it,
their runtimes typically implement a lot of optimisation of CPS code, which
the Perl interpreter would be unable to perform. Instead, CODE references are
passed around to stand in their place. While not particularly useful for most
regular cases, this becomes very useful whenever some form of asynchronous or
event-based programming is being used. Continuations passed in to the body
function of a control structure can be stored in the event handlers of the
asynchronous or event-driven framework, so that when they are invoked later,
the code continues, eventually arriving at its final answer at some point in
the future.
In order for these examples to make sense, a fictional and simple
asynchronisation framework has been invented. The exact details of operation
should not be important, as it simply stands to illustrate the point. I hope
its general intention should be obvious. :)
read_stdin_line( \&on_line ); # wait on a line from STDIN, then pass it
# to the handler function
This module itself provides functions that manage the flow of control through
a continuation passing program. They do not directly facilitate the flow of
data through a program. That can be managed by lexical variables captured by
the closures passed around. See the EXAMPLES section.
For CPS versions of data-flow functionals, such as C<map> and C<grep>, see
also L<CPS::Functional>.
=head1 SYNOPSIS
use CPS qw( kloop );
kloop( sub {
my ( $knext, $klast ) = @_;
print "Enter a number, or q to quit: ";
read_stdin_line( sub {
my ( $first ) = @_;
chomp $first;
return $klast->() if $first eq "q";
print "Enter a second number: ";
read_stdin_line( sub {
my ( $second ) = @_;
print "The sum is " . ( $first + $second ) . "\n";
$knext->();
} );
} );
},
sub { exit }
);
=cut
=head1 FUNCTIONS
In all of the following functions, the C<\&body> function can provide results
by invoking its continuation / one of its continuations, either synchronously
or asynchronously at some point later (via some event handling or other
mechanism); the next invocation of C<\&body> will not take place until the
previous one exits if it is done synchronously.
They all take the prefix C<k> before the name of the regular perl keyword or
function they aim to replace. It is common in CPS code in other languages,
such as Scheme or Haskell, to store a continuation in a variable called C<k>.
This convention is followed here.
=cut
=head2 kloop( \&body, $k )
CPS version of perl's C<while(true)> loop. Repeatedly calls the C<body> code
until it indicates the end of the loop, then invoke C<$k>.
$body->( $knext, $klast )
$knext->()
$klast->()
$k->()
If C<$knext> is invoked, the body will be called again. If C<$klast> is
invoked, the continuation C<$k> is invoked.
=head2 kwhile( \&body, $k )
Compatibility synonym for C<kloop>; it was renamed after version 0.10. New
code should use C<kloop> instead.
=cut
sub _fix
{
my ( $func ) = @_;
sub {
unshift @_, _fix( $func );
goto &$func;
};
}
sub gkloop
{
my ( $gov, $body, $k ) = @_;
# We can't just call this as a method because we need to tailcall it
# Instead, keep a reference to the actual method so we can goto &$enter
my $enter = $gov->can('enter') or croak "Governor cannot ->enter";
my $kfirst = _fix subname gkloop => sub {
my $knext = shift;
my $sync = 1;
my $do_again;
$enter->( $gov, $body,
sub {
if( $sync ) { $do_again=1 }
else { goto &$knext; }
},
sub { @_ = (); goto &$k },
);
$sync = 0;
$k->( @func_ret )
The following are equivalent
print func( 1, 2, 3 );
my $kfunc = liftk( \&func );
$kfunc->( 1, 2, 3, sub { print @_ } );
Note that the returned wrapper function only has one continuation slot in its
arguments. It therefore cannot be used as the body for C<kloop()>,
C<kforeach()> or C<kgenerate()>, because these pass two continuations. There
does not exist a "natural" way to lift a normal call/return function into a
CPS function which requires more than one continuation, because there is no
way to distinguish the different named returns.
=cut
sub liftk(&)
{
my ( $code ) = @_;
return sub {
my $k = pop;
@_ = $code->( @_ );
goto &$k;
};
}
=head2 $func = dropk { BLOCK } $kfunc
=head2 $func = dropk $waitfunc, $kfunc
Returns a new CODE reference to a plain call/return version of the passed
CPS-style CODE reference. When the returned ("dropped") function is called,
it invokes the passed CPS function, then waits for it to invoke its
continuation. When it does, the list that was passed to the continuation is
returned by the dropped function. If called in scalar context, only the first
value in the list is returned.
$kfunc->( @func_args, $k )
$k->( @func_ret )
$waitfunc->()
@func_ret = $func->( @func_args )
Given the following trivial CPS function:
$kadd = sub { $_[2]->( $_[0] + $_[1] ) };
The following are equivalent
$kadd->( 10, 20, sub { print "The total is $_[0]\n" } );
$add = dropk { } $kadd;
print "The total is ".$add->( 10, 20 )."\n";
In the general case the CPS function hasn't yet invoked its continuation by
the time it returns (such as would be the case when using any sort of
asynchronisation or event-driven framework). For C<dropk> to actually work in
this situation, it requires a way to run the event framework, to cause it to
process events until the continuation has been invoked.
This is provided by the block, or the first passed CODE reference. When the
returned function is invoked, it repeatedly calls the block or wait function,
until the CPS function has invoked its continuation.
=cut
sub dropk(&$)
{
my ( $waitfunc, $kfunc ) = @_;
return sub {
my @result;
my $done;
$kfunc->( @_, sub { @result = @_; $done = 1 } );
while( !$done ) {
$waitfunc->();
}
return wantarray ? @result : $result[0];
}
}
=head1 EXAMPLES
=head2 Returning Data From Functions
No facilities are provided directly to return data from CPS body functions in
C<kloop>, C<kpar> and C<kseq>. Instead, normal lexical variable capture may
be used here.
my $bat;
my $ball;
kpar(
sub {
my ( $k ) = @_;
get_bat( on_bat => sub { $bat = shift; goto &$k } );
},
sub {
my ( $k ) = @_;
serve_ball( on_ball => sub { $ball = shift; goto &$k } );
},
sub {
$bat->hit( $ball );
},
);
The body function can set the value of a variable that it and its final
continuation both capture.
=head2 Using C<kseq> For Conditionals
Consider the call/return style of code
( run in 0.555 second using v1.01-cache-2.11-cpan-df04353d9ac )