1CPS(3pm) User Contributed Perl Documentation CPS(3pm)
2
3
4
6 "CPS" - manage flow of control in Continuation-Passing Style
7
9 Note: This module is entirely deprecated now. It is maintained for
10 compatibility for any code still using it, but please consider
11 rewriting to use Future instead, which offers a far neater method
12 of representing asynchronous program and data flow. In addition,
13 Future::AsyncAwait can further improve readability of
14 "Future"-based code by letting it use the familiar kinds of Perl
15 control structure while still being asynchronous.
16
17 At some later date this entire "CPS" module distribution may be
18 deleted.
19
20 The functions in this module implement or assist the writing of
21 programs, or parts of them, in Continuation Passing Style (CPS).
22 Briefly, CPS is a style of writing code where the normal call/return
23 mechanism is replaced by explicit "continuations", values passed in to
24 functions which they should invoke, to implement return behaviour. For
25 more detail on CPS, see the SEE ALSO section.
26
27 What this module implements is not in fact true CPS, as Perl does not
28 natively support the idea of a real continuation (such as is created by
29 a co-routine). Furthermore, for CPS to be efficient in languages that
30 natively support it, their runtimes typically implement a lot of
31 optimisation of CPS code, which the Perl interpreter would be unable to
32 perform. Instead, CODE references are passed around to stand in their
33 place. While not particularly useful for most regular cases, this
34 becomes very useful whenever some form of asynchronous or event-based
35 programming is being used. Continuations passed in to the body function
36 of a control structure can be stored in the event handlers of the
37 asynchronous or event-driven framework, so that when they are invoked
38 later, the code continues, eventually arriving at its final answer at
39 some point in the future.
40
41 In order for these examples to make sense, a fictional and simple
42 asynchronisation framework has been invented. The exact details of
43 operation should not be important, as it simply stands to illustrate
44 the point. I hope its general intention should be obvious. :)
45
46 read_stdin_line( \&on_line ); # wait on a line from STDIN, then pass it
47 # to the handler function
48
49 This module itself provides functions that manage the flow of control
50 through a continuation passing program. They do not directly facilitate
51 the flow of data through a program. That can be managed by lexical
52 variables captured by the closures passed around. See the EXAMPLES
53 section.
54
55 For CPS versions of data-flow functionals, such as "map" and "grep",
56 see also CPS::Functional.
57
59 use CPS qw( kloop );
60
61 kloop( sub {
62 my ( $knext, $klast ) = @_;
63
64 print "Enter a number, or q to quit: ";
65
66 read_stdin_line( sub {
67 my ( $first ) = @_;
68 chomp $first;
69
70 return $klast->() if $first eq "q";
71
72 print "Enter a second number: ";
73
74 read_stdin_line( sub {
75 my ( $second ) = @_;
76
77 print "The sum is " . ( $first + $second ) . "\n";
78
79 $knext->();
80 } );
81 } );
82 },
83 sub { exit }
84 );
85
87 In all of the following functions, the "\&body" function can provide
88 results by invoking its continuation / one of its continuations, either
89 synchronously or asynchronously at some point later (via some event
90 handling or other mechanism); the next invocation of "\&body" will not
91 take place until the previous one exits if it is done synchronously.
92
93 They all take the prefix "k" before the name of the regular perl
94 keyword or function they aim to replace. It is common in CPS code in
95 other languages, such as Scheme or Haskell, to store a continuation in
96 a variable called "k". This convention is followed here.
97
98 kloop( \&body, $k )
99 CPS version of perl's while(true) loop. Repeatedly calls the "body"
100 code until it indicates the end of the loop, then invoke $k.
101
102 $body->( $knext, $klast )
103 $knext->()
104 $klast->()
105
106 $k->()
107
108 If $knext is invoked, the body will be called again. If $klast is
109 invoked, the continuation $k is invoked.
110
111 kwhile( \&body, $k )
112 Compatibility synonym for "kloop"; it was renamed after version 0.10.
113 New code should use "kloop" instead.
114
115 kforeach( \@items, \&body, $k )
116 CPS version of perl's "foreach" loop. Calls the "body" code once for
117 each element in @items, until either the items are exhausted or the
118 "body" invokes its $klast continuation, then invoke $k.
119
120 $body->( $item, $knext, $klast )
121 $knext->()
122 $klast->()
123
124 $k->()
125
126 kdescendd( $root, \&body, $k )
127 CPS version of recursive descent on a tree-like structure, defined by a
128 function, "body", which when given a node in the tree, yields a list of
129 child nodes.
130
131 $body->( $node, $kmore )
132 $kmore->( @child_nodes )
133
134 $k->()
135
136 The first value to be passed into "body" is $root.
137
138 At each iteration, a node is given to the "body" function, and it is
139 expected to pass a list of child nodes into its $kmore continuation.
140 These will then be iterated over, in the order given. The tree-like
141 structure is visited depth-first, descending fully into one subtree of
142 a node before moving on to the next.
143
144 This function does not provide a way for the body to accumulate a
145 resultant data structure to pass into its own continuation. The body is
146 executed simply for its side-effects and its continuation is invoked
147 with no arguments. A variable of some sort should be shared between the
148 body and the continuation if this is required.
149
150 kdescendb( $root, \&body, $k )
151 A breadth-first variation of "kdescendd". This function visits each
152 child node of the parent, before iterating over all of these nodes's
153 children, recursively until the bottom of the tree.
154
155 kpar( @bodies, $k )
156 This CPS function takes a list of function bodies and calls them all
157 immediately. Each is given its own continuation. Once every body has
158 invoked its continuation, the main continuation $k is invoked.
159
160 $body->( $kdone )
161 $kdone->()
162
163 $k->()
164
165 This allows running multiple operations in parallel, and waiting for
166 them all to complete before continuing. It provides in a CPS form
167 functionality similar to that provided in a more object-oriented
168 fashion by modules such as Async::MergePoint or Event::Join.
169
170 kpareach( \@items, \&body, $k )
171 This CPS function takes a list of items and a function body, and calls
172 the body immediately once for each item in the list. Each invocation is
173 given its own continuation. Once every body has invoked its
174 continuation, the main continuation $k is invoked.
175
176 $body->( $item, $kdone )
177 $kdone->()
178
179 $k->()
180
181 This is similar to "kforeach", except that the body is started
182 concurrently for all items in the list list, rather than each item
183 waiting for the previous to finish.
184
185 kseq( @bodies, $k )
186 This CPS function takes a list of function bodies and calls them each,
187 one at a time in sequence. Each is given a continuation to invoke,
188 which will cause the next body to be invoked. When the last body has
189 invoked its continuation, the main continuation $k is invoked.
190
191 $body->( $kdone )
192 $kdone->()
193
194 $k->()
195
196 A benefit of this is that it allows a long operation that uses many
197 continuation "pauses", to be written without code indenting further and
198 further to the right. Another is that it allows easy skipping of
199 conditional parts of a computation, which would otherwise be tricky to
200 write in a CPS form. See the EXAMPLES section.
201
203 All of the above functions are implemented using a loop which
204 repeatedly calls the body function until some terminating condition. By
205 controlling the way this loop re-invokes itself, a program can control
206 the behaviour of the functions.
207
208 For every one of the above functions, there also exists a variant which
209 takes a CPS::Governor object as its first argument. These functions use
210 the governor object to control their iteration.
211
212 kloop( \&body, $k )
213 gkloop( $gov, \&body, $k )
214
215 kforeach( \@items, \&body, $k )
216 gkforeach( $gov, \@items, \&body, $k )
217
218 etc...
219
220 In this way, other governor objects can be constructed which have
221 different running properties; such as interleaving iterations of their
222 loop with other IO activity in an event-driven framework, or giving
223 rate-limitation control on the speed of iteration of the loop.
224
226 These function names do not begin with "k" because they are not
227 themselves CPS primatives, but may be useful in CPS-oriented code.
228
229 $kfunc = liftk { BLOCK }
230 $kfunc = liftk( \&func )
231 Returns a new CODE reference to a CPS-wrapped version of the code block
232 or passed CODE reference. When $kfunc is invoked, the function &func is
233 called in list context, being passed all the arguments given to $kfunc
234 apart from the last, expected to be its continuation. When &func
235 returns, the result is passed into the continuation.
236
237 $kfunc->( @func_args, $k )
238 $k->( @func_ret )
239
240 The following are equivalent
241
242 print func( 1, 2, 3 );
243
244 my $kfunc = liftk( \&func );
245 $kfunc->( 1, 2, 3, sub { print @_ } );
246
247 Note that the returned wrapper function only has one continuation slot
248 in its arguments. It therefore cannot be used as the body for kloop(),
249 kforeach() or kgenerate(), because these pass two continuations. There
250 does not exist a "natural" way to lift a normal call/return function
251 into a CPS function which requires more than one continuation, because
252 there is no way to distinguish the different named returns.
253
254 $func = dropk { BLOCK } $kfunc
255 $func = dropk $waitfunc, $kfunc
256 Returns a new CODE reference to a plain call/return version of the
257 passed CPS-style CODE reference. When the returned ("dropped") function
258 is called, it invokes the passed CPS function, then waits for it to
259 invoke its continuation. When it does, the list that was passed to the
260 continuation is returned by the dropped function. If called in scalar
261 context, only the first value in the list is returned.
262
263 $kfunc->( @func_args, $k )
264 $k->( @func_ret )
265
266 $waitfunc->()
267
268 @func_ret = $func->( @func_args )
269
270 Given the following trivial CPS function:
271
272 $kadd = sub { $_[2]->( $_[0] + $_[1] ) };
273
274 The following are equivalent
275
276 $kadd->( 10, 20, sub { print "The total is $_[0]\n" } );
277
278 $add = dropk { } $kadd;
279 print "The total is ".$add->( 10, 20 )."\n";
280
281 In the general case the CPS function hasn't yet invoked its
282 continuation by the time it returns (such as would be the case when
283 using any sort of asynchronisation or event-driven framework). For
284 "dropk" to actually work in this situation, it requires a way to run
285 the event framework, to cause it to process events until the
286 continuation has been invoked.
287
288 This is provided by the block, or the first passed CODE reference. When
289 the returned function is invoked, it repeatedly calls the block or wait
290 function, until the CPS function has invoked its continuation.
291
293 Returning Data From Functions
294 No facilities are provided directly to return data from CPS body
295 functions in "kloop", "kpar" and "kseq". Instead, normal lexical
296 variable capture may be used here.
297
298 my $bat;
299 my $ball;
300
301 kpar(
302 sub {
303 my ( $k ) = @_;
304 get_bat( on_bat => sub { $bat = shift; goto &$k } );
305 },
306 sub {
307 my ( $k ) = @_;
308 serve_ball( on_ball => sub { $ball = shift; goto &$k } );
309 },
310
311 sub {
312 $bat->hit( $ball );
313 },
314 );
315
316 The body function can set the value of a variable that it and its final
317 continuation both capture.
318
319 Using "kseq" For Conditionals
320 Consider the call/return style of code
321
322 A();
323 if( $maybe ) {
324 B();
325 }
326 C();
327
328 We cannot easily write this in CPS form without naming C twice
329
330 kA( sub {
331 $maybe ?
332 kB( sub { kC() } ) :
333 kC();
334 } );
335
336 While not so problematic here, it could get awkward if C were in fact a
337 large code block, or if more than a single conditional were employed in
338 the logic; a likely scenario. A further issue is that the logical
339 structure becomes much harder to read.
340
341 Using "kseq" allows us to name the continuation so each arm of "kmaybe"
342 can invoke it indirectly.
343
344 kseq(
345 \&kA,
346 sub { my $k = shift; $maybe ? kB( $k ) : goto &$k; },
347 \&kC
348 );
349
351 • Future - represent an operation awaiting completion
352
353 • Future::AsyncAwait - deferred subroutine syntax for futures
354
355 • CPS::Functional - functional utilities in Continuation-Passing
356 Style
357
358 • <http://en.wikipedia.org/wiki/Continuation-passing_style> on
359 wikipedia
360
362 Matt S. Trout (mst) <mst@shadowcat.co.uk> - for the inspiration of
363 "kpareach" and with apologies to for naming of the said. ;)
364
366 Paul Evans <leonerd@leonerd.org.uk>
367
368
369
370perl v5.38.0 2023-07-20 CPS(3pm)