.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.42) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "CPS 3pm" .TH CPS 3pm "2022-06-30" "perl v5.34.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" "CPS" \- manage flow of control in Continuation\-Passing Style .SH "OVERVIEW" .IX Header "OVERVIEW" .RS 4 \&\fBNote\fR: This module is entirely deprecated now. It is maintained for compatibility for any code still using it, but please consider rewriting to use Future instead, which offers a far neater method of representing asynchronous program and data flow. In addition, Future::AsyncAwait can further improve readability of \f(CW\*(C`Future\*(C'\fR\-based code by letting it use the familiar kinds of Perl control structure while still being asynchronous. .Sp At some later date this entire \f(CW\*(C`CPS\*(C'\fR module distribution may be deleted. .RE .PP The functions in this module implement or assist the writing of programs, or parts of them, in Continuation Passing Style (\s-1CPS\s0). Briefly, \s-1CPS\s0 is a style of writing code where the normal call/return mechanism is replaced by explicit \&\*(L"continuations\*(R", values passed in to functions which they should invoke, to implement return behaviour. For more detail on \s-1CPS,\s0 see the \s-1SEE ALSO\s0 section. .PP What this module implements is not in fact true \s-1CPS,\s0 as Perl does not natively support the idea of a real continuation (such as is created by a co-routine). Furthermore, for \s-1CPS\s0 to be efficient in languages that natively support it, their runtimes typically implement a lot of optimisation of \s-1CPS\s0 code, which the Perl interpreter would be unable to perform. Instead, \s-1CODE\s0 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. .PP 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. :) .PP .Vb 2 \& read_stdin_line( \e&on_line ); # wait on a line from STDIN, then pass it \& # to the handler function .Ve .PP 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 \s-1EXAMPLES\s0 section. .PP For \s-1CPS\s0 versions of data-flow functionals, such as \f(CW\*(C`map\*(C'\fR and \f(CW\*(C`grep\*(C'\fR, see also CPS::Functional. .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& 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 ) . "\en"; \& \& $knext\->(); \& } ); \& } ); \& }, \& sub { exit } \& ); .Ve .SH "FUNCTIONS" .IX Header "FUNCTIONS" In all of the following functions, the \f(CW\*(C`\e&body\*(C'\fR 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 \f(CW\*(C`\e&body\*(C'\fR will not take place until the previous one exits if it is done synchronously. .PP They all take the prefix \f(CW\*(C`k\*(C'\fR before the name of the regular perl keyword or function they aim to replace. It is common in \s-1CPS\s0 code in other languages, such as Scheme or Haskell, to store a continuation in a variable called \f(CW\*(C`k\*(C'\fR. This convention is followed here. .ie n .SS "kloop( \e&body, $k )" .el .SS "kloop( \e&body, \f(CW$k\fP )" .IX Subsection "kloop( &body, $k )" \&\s-1CPS\s0 version of perl's \f(CW\*(C`while(true)\*(C'\fR loop. Repeatedly calls the \f(CW\*(C`body\*(C'\fR code until it indicates the end of the loop, then invoke \f(CW$k\fR. .PP .Vb 3 \& $body\->( $knext, $klast ) \& $knext\->() \& $klast\->() \& \& $k\->() .Ve .PP If \f(CW$knext\fR is invoked, the body will be called again. If \f(CW$klast\fR is invoked, the continuation \f(CW$k\fR is invoked. .ie n .SS "kwhile( \e&body, $k )" .el .SS "kwhile( \e&body, \f(CW$k\fP )" .IX Subsection "kwhile( &body, $k )" Compatibility synonym for \f(CW\*(C`kloop\*(C'\fR; it was renamed after version 0.10. New code should use \f(CW\*(C`kloop\*(C'\fR instead. .ie n .SS "kforeach( \e@items, \e&body, $k )" .el .SS "kforeach( \e@items, \e&body, \f(CW$k\fP )" .IX Subsection "kforeach( @items, &body, $k )" \&\s-1CPS\s0 version of perl's \f(CW\*(C`foreach\*(C'\fR loop. Calls the \f(CW\*(C`body\*(C'\fR code once for each element in \f(CW@items\fR, until either the items are exhausted or the \f(CW\*(C`body\*(C'\fR invokes its \f(CW$klast\fR continuation, then invoke \f(CW$k\fR. .PP .Vb 3 \& $body\->( $item, $knext, $klast ) \& $knext\->() \& $klast\->() \& \& $k\->() .Ve .ie n .SS "kdescendd( $root, \e&body, $k )" .el .SS "kdescendd( \f(CW$root\fP, \e&body, \f(CW$k\fP )" .IX Subsection "kdescendd( $root, &body, $k )" \&\s-1CPS\s0 version of recursive descent on a tree-like structure, defined by a function, \f(CW\*(C`body\*(C'\fR, which when given a node in the tree, yields a list of child nodes. .PP .Vb 2 \& $body\->( $node, $kmore ) \& $kmore\->( @child_nodes ) \& \& $k\->() .Ve .PP The first value to be passed into \f(CW\*(C`body\*(C'\fR is \f(CW$root\fR. .PP At each iteration, a node is given to the \f(CW\*(C`body\*(C'\fR function, and it is expected to pass a list of child nodes into its \f(CW$kmore\fR continuation. These will then be iterated over, in the order given. The tree-like structure is visited depth-first, descending fully into one subtree of a node before moving on to the next. .PP This function does not provide a way for the body to accumulate a resultant data structure to pass into its own continuation. The body is executed simply for its side-effects and its continuation is invoked with no arguments. A variable of some sort should be shared between the body and the continuation if this is required. .ie n .SS "kdescendb( $root, \e&body, $k )" .el .SS "kdescendb( \f(CW$root\fP, \e&body, \f(CW$k\fP )" .IX Subsection "kdescendb( $root, &body, $k )" A breadth-first variation of \f(CW\*(C`kdescendd\*(C'\fR. This function visits each child node of the parent, before iterating over all of these nodes's children, recursively until the bottom of the tree. .ie n .SS "kpar( @bodies, $k )" .el .SS "kpar( \f(CW@bodies\fP, \f(CW$k\fP )" .IX Subsection "kpar( @bodies, $k )" This \s-1CPS\s0 function takes a list of function bodies and calls them all immediately. Each is given its own continuation. Once every body has invoked its continuation, the main continuation \f(CW$k\fR is invoked. .PP .Vb 2 \& $body\->( $kdone ) \& $kdone\->() \& \& $k\->() .Ve .PP This allows running multiple operations in parallel, and waiting for them all to complete before continuing. It provides in a \s-1CPS\s0 form functionality similar to that provided in a more object-oriented fashion by modules such as Async::MergePoint or Event::Join. .ie n .SS "kpareach( \e@items, \e&body, $k )" .el .SS "kpareach( \e@items, \e&body, \f(CW$k\fP )" .IX Subsection "kpareach( @items, &body, $k )" This \s-1CPS\s0 function takes a list of items and a function body, and calls the body immediately once for each item in the list. Each invocation is given its own continuation. Once every body has invoked its continuation, the main continuation \f(CW$k\fR is invoked. .PP .Vb 2 \& $body\->( $item, $kdone ) \& $kdone\->() \& \& $k\->() .Ve .PP This is similar to \f(CW\*(C`kforeach\*(C'\fR, except that the body is started concurrently for all items in the list list, rather than each item waiting for the previous to finish. .ie n .SS "kseq( @bodies, $k )" .el .SS "kseq( \f(CW@bodies\fP, \f(CW$k\fP )" .IX Subsection "kseq( @bodies, $k )" This \s-1CPS\s0 function takes a list of function bodies and calls them each, one at a time in sequence. Each is given a continuation to invoke, which will cause the next body to be invoked. When the last body has invoked its continuation, the main continuation \f(CW$k\fR is invoked. .PP .Vb 2 \& $body\->( $kdone ) \& $kdone\->() \& \& $k\->() .Ve .PP A benefit of this is that it allows a long operation that uses many continuation \*(L"pauses\*(R", to be written without code indenting further and further to the right. Another is that it allows easy skipping of conditional parts of a computation, which would otherwise be tricky to write in a \s-1CPS\s0 form. See the \s-1EXAMPLES\s0 section. .SH "GOVERNORS" .IX Header "GOVERNORS" All of the above functions are implemented using a loop which repeatedly calls the body function until some terminating condition. By controlling the way this loop re-invokes itself, a program can control the behaviour of the functions. .PP For every one of the above functions, there also exists a variant which takes a CPS::Governor object as its first argument. These functions use the governor object to control their iteration. .PP .Vb 2 \& kloop( \e&body, $k ) \& gkloop( $gov, \e&body, $k ) \& \& kforeach( \e@items, \e&body, $k ) \& gkforeach( $gov, \e@items, \e&body, $k ) \& \& etc... .Ve .PP In this way, other governor objects can be constructed which have different running properties; such as interleaving iterations of their loop with other \&\s-1IO\s0 activity in an event-driven framework, or giving rate-limitation control on the speed of iteration of the loop. .SH "CPS UTILITIES" .IX Header "CPS UTILITIES" These function names do not begin with \f(CW\*(C`k\*(C'\fR because they are not themselves \&\s-1CPS\s0 primatives, but may be useful in CPS-oriented code. .ie n .SS "$kfunc = liftk { \s-1BLOCK\s0 }" .el .SS "\f(CW$kfunc\fP = liftk { \s-1BLOCK\s0 }" .IX Subsection "$kfunc = liftk { BLOCK }" .ie n .SS "$kfunc = liftk( \e&func )" .el .SS "\f(CW$kfunc\fP = liftk( \e&func )" .IX Subsection "$kfunc = liftk( &func )" Returns a new \s-1CODE\s0 reference to a CPS-wrapped version of the code block or passed \s-1CODE\s0 reference. When \f(CW$kfunc\fR is invoked, the function \f(CW&func\fR is called in list context, being passed all the arguments given to \f(CW$kfunc\fR apart from the last, expected to be its continuation. When \f(CW&func\fR returns, the result is passed into the continuation. .PP .Vb 2 \& $kfunc\->( @func_args, $k ) \& $k\->( @func_ret ) .Ve .PP The following are equivalent .PP .Vb 1 \& print func( 1, 2, 3 ); \& \& my $kfunc = liftk( \e&func ); \& $kfunc\->( 1, 2, 3, sub { print @_ } ); .Ve .PP Note that the returned wrapper function only has one continuation slot in its arguments. It therefore cannot be used as the body for \f(CW\*(C`kloop()\*(C'\fR, \&\f(CW\*(C`kforeach()\*(C'\fR or \f(CW\*(C`kgenerate()\*(C'\fR, because these pass two continuations. There does not exist a \*(L"natural\*(R" way to lift a normal call/return function into a \&\s-1CPS\s0 function which requires more than one continuation, because there is no way to distinguish the different named returns. .ie n .SS "$func = dropk { \s-1BLOCK\s0 } $kfunc" .el .SS "\f(CW$func\fP = dropk { \s-1BLOCK\s0 } \f(CW$kfunc\fP" .IX Subsection "$func = dropk { BLOCK } $kfunc" .ie n .SS "$func = dropk $waitfunc, $kfunc" .el .SS "\f(CW$func\fP = dropk \f(CW$waitfunc\fP, \f(CW$kfunc\fP" .IX Subsection "$func = dropk $waitfunc, $kfunc" Returns a new \s-1CODE\s0 reference to a plain call/return version of the passed CPS-style \s-1CODE\s0 reference. When the returned (\*(L"dropped\*(R") function is called, it invokes the passed \s-1CPS\s0 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. .PP .Vb 2 \& $kfunc\->( @func_args, $k ) \& $k\->( @func_ret ) \& \& $waitfunc\->() \& \& @func_ret = $func\->( @func_args ) .Ve .PP Given the following trivial \s-1CPS\s0 function: .PP .Vb 1 \& $kadd = sub { $_[2]\->( $_[0] + $_[1] ) }; .Ve .PP The following are equivalent .PP .Vb 1 \& $kadd\->( 10, 20, sub { print "The total is $_[0]\en" } ); \& \& $add = dropk { } $kadd; \& print "The total is ".$add\->( 10, 20 )."\en"; .Ve .PP In the general case the \s-1CPS\s0 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 \f(CW\*(C`dropk\*(C'\fR 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. .PP This is provided by the block, or the first passed \s-1CODE\s0 reference. When the returned function is invoked, it repeatedly calls the block or wait function, until the \s-1CPS\s0 function has invoked its continuation. .SH "EXAMPLES" .IX Header "EXAMPLES" .SS "Returning Data From Functions" .IX Subsection "Returning Data From Functions" No facilities are provided directly to return data from \s-1CPS\s0 body functions in \&\f(CW\*(C`kloop\*(C'\fR, \f(CW\*(C`kpar\*(C'\fR and \f(CW\*(C`kseq\*(C'\fR. Instead, normal lexical variable capture may be used here. .PP .Vb 2 \& 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 ); \& }, \& ); .Ve .PP The body function can set the value of a variable that it and its final continuation both capture. .ie n .SS "Using ""kseq"" For Conditionals" .el .SS "Using \f(CWkseq\fP For Conditionals" .IX Subsection "Using kseq For Conditionals" Consider the call/return style of code .PP .Vb 5 \& A(); \& if( $maybe ) { \& B(); \& } \& C(); .Ve .PP We cannot easily write this in \s-1CPS\s0 form without naming C twice .PP .Vb 5 \& kA( sub { \& $maybe ? \& kB( sub { kC() } ) : \& kC(); \& } ); .Ve .PP While not so problematic here, it could get awkward if C were in fact a large code block, or if more than a single conditional were employed in the logic; a likely scenario. A further issue is that the logical structure becomes much harder to read. .PP Using \f(CW\*(C`kseq\*(C'\fR allows us to name the continuation so each arm of \f(CW\*(C`kmaybe\*(C'\fR can invoke it indirectly. .PP .Vb 5 \& kseq( \& \e&kA, \& sub { my $k = shift; $maybe ? kB( $k ) : goto &$k; }, \& \e&kC \& ); .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "\(bu" 4 Future \- represent an operation awaiting completion .IP "\(bu" 4 Future::AsyncAwait \- deferred subroutine syntax for futures .IP "\(bu" 4 CPS::Functional \- functional utilities in Continuation-Passing Style .IP "\(bu" 4 on wikipedia .SH "ACKNOWLEDGEMENTS" .IX Header "ACKNOWLEDGEMENTS" Matt S. Trout (mst) \- for the inspiration of \f(CW\*(C`kpareach\*(C'\fR and with apologies to for naming of the said. ;) .SH "AUTHOR" .IX Header "AUTHOR" Paul Evans