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