CPS-0.19000755001750001750 013470501137 10612 5ustar00leoleo000000000000CPS-0.19/Build.PL000444001750001750 101113470501137 12234 0ustar00leoleo000000000000use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => 'CPS', recommends => { 'Sub::Name' => 0, }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, test_requires => { 'Test::Identity' => 0, 'Test::Fatal' => 0, 'Test::More' => 0, 'Test::Refcount' => 0, }, requires => { 'Future' => 0, }, license => 'perl', create_license => 1, create_readme => 1, ); $build->create_build_script; CPS-0.19/Changes000444001750001750 635313470501137 12251 0ustar00leoleo000000000000Revision history for CPS 0.19 2019-05-20 11:31:46 [CHANGES] * Removed CPS::Future and unit test for it * Added deprecation warning and SEE ALSO links to Future and Future::AsyncAwait * Build script updates and unit test style fixes 0.18 CHANGES: * Moved CPS::Future out to its own distribution, Future. Retained a small back-compat wrapper for now * Implement gkpar in terms of gkforeach so it respects the governor's ->enter method 0.17 CHANGES: * Supply ->done_cb, ->fail_cb, ->cancel_cb callback-generation methods to CPS::Future * Allow future chaining for cancellation 0.16 CHANGES: * Allow passing CPS::Future objects into others for on_ready, on_done and on_fail callbacks (RT78432) * Override calling on a CPS::Future to invoke ->done directly 0.15 CHANGES: * More work on CPS::Future - added ->and_then, ->transform 0.14 CHANGES: * Handle Carp 1.25's new message format - RT 75377 0.13 CHANGES: * More work on CPS::Future - added cancellation, on_fail/on_done, needs_all constructor * Also build_requires Test::Fatal 0.12 CHANGES: * Some initial work on CPS::Future 0.11 CHANGES: * Added kpareach() * Renamed kloop() to kwhile(); added transparent back-compatibility redirect 0.10 CHANGES: * Moved data-flow functional functions into their own CPS::Functional namespace * Don't check ref($k) eq "CODE" - may get in the way of Clever Tricks (e.g. callable objects) BUGFIXES: * Scrub @_ in continuation from kwhile() and kpar() - fixes RT 55787 * Implement gkwhile() using a fixpoint combinator to avoid weakref bugs on perl 5.6 entirely 0.09 CHANGES: * Added kseq() * Minor documentation updates * Skip t/32leakcheck.t before perl version 5.8.0 0.08 CHANGES: * Added kpar() * Only opportunisticly use Sub::Name, don't hard-depend on it in case of pure-perl scenarios 0.07 CHANGES: * Added note about perl before 5.8 not implementing weaken properly, so possible memory leaks if gkwhile()'s continuations are lost BUGFIXES: * Second attempt at making gkwhile() work on perl 5.6 0.06 CHANGES: * Created CPS::Governor::Deferred * Use Sub::Name to correctly name the gkwhile iteration closure 0.05 CHANGES: * Added kdescendd() and kdescendb() * (Hopefully) work on perl 5.6 again * Created the concept of a Governor and implemented a simple one 0.04 CHANGES: * Added dropk() analogous to liftk() * Added 'use warnings' * Various small updates to keep CPANTS happy 0.03 BUGFIXES: * Declare dependency on at least perl 5.8 since weaken() fails tests on earlier perls 0.02 CHANGES: * Use Scalar::Util::weaken() in kwhile(), breaking cycle for $iter and allowing body to care less about leaks. Also allows passthrough of $k without intermediate sub{} 0.01 First version, released on an unsuspecting world. CPS-0.19/LICENSE000444001750001750 4376213470501137 12010 0ustar00leoleo000000000000This software is copyright (c) 2019 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2019 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2019 by Paul Evans . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End CPS-0.19/MANIFEST000444001750001750 73113470501137 12061 0ustar00leoleo000000000000Build.PL Changes examples/kforeach.pl lib/CPS.pm lib/CPS/Functional.pm lib/CPS/Governor.pm lib/CPS/Governor/Deferred.pm lib/CPS/Governor/Simple.pm LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01kloop.t t/02kforeach.t t/03kdescend.t t/04kpar.t t/05kpareach.t t/06kseq.t t/10liftk.t t/11dropk.t t/20governor-simple.t t/21governor-deferred.t t/30governor.t t/31caller.t t/32leakcheck.t t/40kmap.t t/41kgrep.t t/42kfold.t t/43kunfold.t t/99pod.t CPS-0.19/META.json000444001750001750 314313470501137 12371 0ustar00leoleo000000000000{ "abstract" : "manage flow of control in Continuation-Passing Style", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "CPS", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "recommends" : { "Sub::Name" : "0" }, "requires" : { "Future" : "0" } }, "test" : { "requires" : { "Test::Fatal" : "0", "Test::Identity" : "0", "Test::More" : "0", "Test::Refcount" : "0" } } }, "provides" : { "CPS" : { "file" : "lib/CPS.pm", "version" : "0.19" }, "CPS::Functional" : { "file" : "lib/CPS/Functional.pm", "version" : "0.19" }, "CPS::Governor" : { "file" : "lib/CPS/Governor.pm", "version" : "0.19" }, "CPS::Governor::Deferred" : { "file" : "lib/CPS/Governor/Deferred.pm", "version" : "0.19" }, "CPS::Governor::Simple" : { "file" : "lib/CPS/Governor/Simple.pm", "version" : "0.19" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.19", "x_serialization_backend" : "JSON::PP version 4.00" } CPS-0.19/META.yml000444001750001750 177713470501137 12234 0ustar00leoleo000000000000--- abstract: 'manage flow of control in Continuation-Passing Style' author: - 'Paul Evans ' build_requires: Test::Fatal: '0' Test::Identity: '0' Test::More: '0' Test::Refcount: '0' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: CPS provides: CPS: file: lib/CPS.pm version: '0.19' CPS::Functional: file: lib/CPS/Functional.pm version: '0.19' CPS::Governor: file: lib/CPS/Governor.pm version: '0.19' CPS::Governor::Deferred: file: lib/CPS/Governor/Deferred.pm version: '0.19' CPS::Governor::Simple: file: lib/CPS/Governor/Simple.pm version: '0.19' recommends: Sub::Name: '0' requires: Future: '0' resources: license: http://dev.perl.org/licenses/ version: '0.19' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' CPS-0.19/README000444001750001750 3226713470501137 11661 0ustar00leoleo000000000000NAME CPS - manage flow of control in Continuation-Passing Style OVERVIEW Note: 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 Future-based code by letting it use the familiar kinds of Perl control structure while still being asynchronous. At some later date this entire CPS module distribution may be deleted. 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 map and grep, see also CPS::Functional. 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 } ); FUNCTIONS In all of the following functions, the \&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 \&body will not take place until the previous one exits if it is done synchronously. They all take the prefix 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 k. This convention is followed here. kloop( \&body, $k ) CPS version of perl's while(true) loop. Repeatedly calls the body code until it indicates the end of the loop, then invoke $k. $body->( $knext, $klast ) $knext->() $klast->() $k->() If $knext is invoked, the body will be called again. If $klast is invoked, the continuation $k is invoked. kwhile( \&body, $k ) Compatibility synonym for kloop; it was renamed after version 0.10. New code should use kloop instead. kforeach( \@items, \&body, $k ) CPS version of perl's foreach loop. Calls the body code once for each element in @items, until either the items are exhausted or the body invokes its $klast continuation, then invoke $k. $body->( $item, $knext, $klast ) $knext->() $klast->() $k->() kdescendd( $root, \&body, $k ) CPS version of recursive descent on a tree-like structure, defined by a function, body, which when given a node in the tree, yields a list of child nodes. $body->( $node, $kmore ) $kmore->( @child_nodes ) $k->() The first value to be passed into body is $root. At each iteration, a node is given to the body function, and it is expected to pass a list of child nodes into its $kmore 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. 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. kdescendb( $root, \&body, $k ) A breadth-first variation of kdescendd. 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. kpar( @bodies, $k ) This CPS 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 $k is invoked. $body->( $kdone ) $kdone->() $k->() This allows running multiple operations in parallel, and waiting for them all to complete before continuing. It provides in a CPS form functionality similar to that provided in a more object-oriented fashion by modules such as Async::MergePoint or Event::Join. kpareach( \@items, \&body, $k ) This CPS 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 $k is invoked. $body->( $item, $kdone ) $kdone->() $k->() This is similar to kforeach, except that the body is started concurrently for all items in the list list, rather than each item waiting for the previous to finish. kseq( @bodies, $k ) This CPS 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 $k is invoked. $body->( $kdone ) $kdone->() $k->() A benefit of this is that it allows a long operation that uses many continuation "pauses", 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 CPS form. See the EXAMPLES section. 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. 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. kloop( \&body, $k ) gkloop( $gov, \&body, $k ) kforeach( \@items, \&body, $k ) gkforeach( $gov, \@items, \&body, $k ) etc... In this way, other governor objects can be constructed which have different running properties; such as interleaving iterations of their loop with other IO activity in an event-driven framework, or giving rate-limitation control on the speed of iteration of the loop. CPS UTILITIES These function names do not begin with k because they are not themselves CPS primatives, but may be useful in CPS-oriented code. $kfunc = liftk { BLOCK } $kfunc = liftk( \&func ) Returns a new CODE reference to a CPS-wrapped version of the code block or passed CODE reference. When $kfunc is invoked, the function &func is called in list context, being passed all the arguments given to $kfunc apart from the last, expected to be its continuation. When &func returns, the result is passed into the continuation. $kfunc->( @func_args, $k ) $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 kloop(), kforeach() or 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. $func = dropk { BLOCK } $kfunc $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 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. EXAMPLES Returning Data From Functions No facilities are provided directly to return data from CPS body functions in kloop, kpar and 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. Using kseq For Conditionals Consider the call/return style of code A(); if( $maybe ) { B(); } C(); We cannot easily write this in CPS form without naming C twice kA( sub { $maybe ? kB( sub { kC() } ) : kC(); } ); 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. Using kseq allows us to name the continuation so each arm of kmaybe can invoke it indirectly. kseq( \&kA, sub { my $k = shift; $maybe ? kB( $k ) : goto &$k; }, \&kC ); SEE ALSO * Future - represent an operation awaiting completion * Future::AsyncAwait - deferred subroutine syntax for futures * CPS::Functional - functional utilities in Continuation-Passing Style * http://en.wikipedia.org/wiki/Continuation-passing_style on wikipedia ACKNOWLEDGEMENTS Matt S. Trout (mst) - for the inspiration of kpareach and with apologies to for naming of the said. ;) AUTHOR Paul Evans CPS-0.19/examples000755001750001750 013470501137 12430 5ustar00leoleo000000000000CPS-0.19/examples/kforeach.pl000444001750001750 67613470501137 14675 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use CPS qw( gkforeach kpar ); use CPS::Governor::Deferred; my $gov = CPS::Governor::Deferred->new; gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "A$item "; goto &$knext; }, sub {}, ); gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "B$item "; goto &$knext; }, sub {}, ); $gov->flush; print "\n"; CPS-0.19/lib000755001750001750 013470501137 11360 5ustar00leoleo000000000000CPS-0.19/lib/CPS.pm000444001750001750 4245013470501137 12525 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (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 - manage flow of control in Continuation-Passing Style =head1 OVERVIEW =over 4 B: This module is entirely deprecated now. It is maintained for compatibility for any code still using it, but please consider rewriting to use L instead, which offers a far neater method of representing asynchronous program and data flow. In addition, L can further improve readability of C-based code by letting it use the familiar kinds of Perl control structure while still being asynchronous. At some later date this entire C 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 and C, see also L. =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 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. This convention is followed here. =cut =head2 kloop( \&body, $k ) CPS version of perl's C loop. Repeatedly calls the C 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; it was renamed after version 0.10. New code should use C 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; if( $do_again ) { $do_again = 0; goto &$knext; } }; goto &$kfirst; } *gkwhile = \&gkloop; =head2 kforeach( \@items, \&body, $k ) CPS version of perl's C loop. Calls the C code once for each element in C<@items>, until either the items are exhausted or the C invokes its C<$klast> continuation, then invoke C<$k>. $body->( $item, $knext, $klast ) $knext->() $klast->() $k->() =cut sub gkforeach { my ( $gov, $items, $body, $k ) = @_; my $idx = 0; gkloop( $gov, sub { my ( $knext, $klast ) = @_; goto &$klast unless $idx < scalar @$items; @_ =( $items->[$idx++], $knext, $klast ); goto &$body; }, $k, ); } =head2 kdescendd( $root, \&body, $k ) CPS version of recursive descent on a tree-like structure, defined by a function, C, which when given a node in the tree, yields a list of child nodes. $body->( $node, $kmore ) $kmore->( @child_nodes ) $k->() The first value to be passed into C is C<$root>. At each iteration, a node is given to the C function, and it is expected to pass a list of child nodes into its C<$kmore> 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. 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. =cut sub gkdescendd { my ( $gov, $root, $body, $k ) = @_; my @stack = ( $root ); gkloop( $gov, sub { my ( $knext, $klast ) = @_; @_ = ( shift @stack, sub { unshift @stack, @_; goto &$knext if @stack; goto &$klast; }, ); goto &$body; }, $k, ); } =head2 kdescendb( $root, \&body, $k ) A breadth-first variation of C. 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. =cut sub gkdescendb { my ( $gov, $root, $body, $k ) = @_; my @queue = ( $root ); gkloop( $gov, sub { my ( $knext, $klast ) = @_; @_ = ( shift @queue, sub { push @queue, @_; goto &$knext if @queue; goto &$klast; }, ); goto &$body; }, $k, ); } =head2 kpar( @bodies, $k ) This CPS 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 C<$k> is invoked. $body->( $kdone ) $kdone->() $k->() This allows running multiple operations in parallel, and waiting for them all to complete before continuing. It provides in a CPS form functionality similar to that provided in a more object-oriented fashion by modules such as L or L. =cut sub gkpar { my ( $gov, @bodies ) = @_; my $k = pop @bodies; $gov->can('enter') or croak "Governor cannot ->enter"; my $sync = 1; my @outstanding; my $kdone = sub { return if $sync; $_ and return for @outstanding; goto &$k; }; gkforeach( $gov, [ 0 .. $#bodies ], sub { my ( $idx, $knext ) = @_; $outstanding[$idx]++; $gov->enter( $bodies[$idx], sub { $outstanding[$idx]--; @_ = (); goto &$kdone; } ); goto &$knext; }, sub { $sync = 0; @_ = (); goto &$kdone; } ); } =head2 kpareach( \@items, \&body, $k ) This CPS 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 C<$k> is invoked. $body->( $item, $kdone ) $kdone->() $k->() This is similar to C, except that the body is started concurrently for all items in the list list, rather than each item waiting for the previous to finish. =cut sub gkpareach { my ( $gov, $items, $body, $k ) = @_; gkpar( $gov, (map { my $item = $_; sub { unshift @_, $item; goto &$body } } @$items), $k ); } =head2 kseq( @bodies, $k ) This CPS 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 C<$k> is invoked. $body->( $kdone ) $kdone->() $k->() A benefit of this is that it allows a long operation that uses many continuation "pauses", 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 CPS form. See the EXAMPLES section. =cut sub gkseq { my ( $gov, @bodies ) = @_; my $k = pop @bodies; my $enter = $gov->can('enter') or croak "Governor cannot ->enter"; while( @bodies ) { my $nextk = $k; my $b = pop @bodies; $k = sub { @_ = ( $gov, $b, $nextk ); goto &$enter; }; } @_ = (); goto &$k; } =head1 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. For every one of the above functions, there also exists a variant which takes a L object as its first argument. These functions use the governor object to control their iteration. kloop( \&body, $k ) gkloop( $gov, \&body, $k ) kforeach( \@items, \&body, $k ) gkforeach( $gov, \@items, \&body, $k ) etc... In this way, other governor objects can be constructed which have different running properties; such as interleaving iterations of their loop with other IO activity in an event-driven framework, or giving rate-limitation control on the speed of iteration of the loop. =cut # The above is a lie. The basic functions provided are actually the gk* # versions; we wrap these to make the normal k* functions by passing a simple # governor. sub _governate { my $pkg = caller; my ( $func, $name ) = @_; my $default_gov = CPS::Governor::Simple->new; no strict 'refs'; my $code = $pkg->can( $func ) or croak "$pkg cannot $func()"; *{$pkg."::$name"} = subname $name => sub { unshift @_, $default_gov; goto &$code; }; } _governate "g$_" => $_ for @CPS_PRIMS; =head1 CPS UTILITIES These function names do not begin with C because they are not themselves CPS primatives, but may be useful in CPS-oriented code. =cut =head2 $kfunc = liftk { BLOCK } =head2 $kfunc = liftk( \&func ) Returns a new CODE reference to a CPS-wrapped version of the code block or passed CODE reference. When C<$kfunc> is invoked, the function C<&func> is called in list context, being passed all the arguments given to C<$kfunc> apart from the last, expected to be its continuation. When C<&func> returns, the result is passed into the continuation. $kfunc->( @func_args, $k ) $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, C or C, 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 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, C and C. 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 For Conditionals Consider the call/return style of code A(); if( $maybe ) { B(); } C(); We cannot easily write this in CPS form without naming C twice kA( sub { $maybe ? kB( sub { kC() } ) : kC(); } ); 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. Using C allows us to name the continuation so each arm of C can invoke it indirectly. kseq( \&kA, sub { my $k = shift; $maybe ? kB( $k ) : goto &$k; }, \&kC ); =head1 SEE ALSO =over 4 =item * L - represent an operation awaiting completion =item * L - deferred subroutine syntax for futures =item * L - functional utilities in Continuation-Passing Style =item * L on wikipedia =back =head1 ACKNOWLEDGEMENTS Matt S. Trout (mst) - for the inspiration of C and with apologies to for naming of the said. ;) =head1 AUTHOR Paul Evans =cut 0x55AA; CPS-0.19/lib/CPS000755001750001750 013470501137 12005 5ustar00leoleo000000000000CPS-0.19/lib/CPS/Functional.pm000444001750001750 2561613470501137 14634 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2010 -- leonerd@leonerd.org.uk package CPS::Functional; use strict; use warnings; our $VERSION = '0.19'; use Carp; use Exporter 'import'; use CPS qw( gkloop ); our @CPS_PRIMS = qw( kmap kgrep kfoldl kfoldr kunfold ); our @EXPORT_OK = ( @CPS_PRIMS, map( "g$_", @CPS_PRIMS ), ); # 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 - functional utilities in Continuation-Passing Style =head1 SYNOPSIS use CPS::Functional qw( kmap ); use Example::HTTP::Client qw( k_get_http ); use List::Util qw( sum ); my @URLs = ( "http://www.foo.com", "http://www.bar.com", ); kmap( \@URLs, sub { my ( $item, $kret ) = @_; k_get_http( uri => $item, on_response => sub { my ( $response ) = @_; $kret->( $response->content_length ); } ); }, sub { my ( @sizes ) = @_; say "Total length of all URLs: " . sum(@sizes); }, ); =head1 DESCRIPTION This module provides L versions of data-flow functionals, such as Perl's C and C, where function bodies are invoked and expected to return data, which the functional manages. They are built on top of the control-flow functionals provided by the C module itself. =cut =head1 FUNCTIONS =cut =head2 kmap( \@items, \&body, $k ) CPS version of perl's C statement. Calls the C code once for each element in C<@items>, capturing the list of values the body passes into its continuation. When the items are exhausted, C<$k> is invoked and passed a list of all the collected values. $body->( $item, $kret ) $kret->( @items_out ) $k->( @all_items_out ) =cut sub gkmap { my ( $gov, $items, $body, $k ) = @_; ref $items eq "ARRAY" or croak 'Expected $items as ARRAY ref'; ref $body eq "CODE" or croak 'Expected $body as CODE ref'; my @ret; my $idx = 0; gkloop( $gov, sub { my ( $knext, $klast ) = @_; goto &$klast unless $idx < scalar @$items; @_ = ( $items->[$idx++], sub { push @ret, @_; goto &$knext } ); goto &$body; }, sub { $k->( @ret ) }, ); } =head2 kgrep( \@items, \&body, $k ) CPS version of perl's C statement. Calls the C code once for each element in C<@items>, capturing those elements where the body's continuation was invoked with a true value. When the items are exhausted, C<$k> is invoked and passed a list of the subset of C<@items> which were selected. $body->( $item, $kret ) $kret->( $select ) $k->( @chosen_items ) =cut sub gkgrep { my ( $gov, $items, $body, $k ) = @_; ref $items eq "ARRAY" or croak 'Expected $items as ARRAY ref'; ref $body eq "CODE" or croak 'Expected $body as CODE ref'; my @ret; my $idx = 0; gkloop( $gov, sub { my ( $knext, $klast ) = @_; goto &$klast unless $idx < scalar @$items; my $item = $items->[$idx++]; @_ = ( $item, sub { push @ret, $item if $_[0]; goto &$knext } ); goto &$body; }, sub { $k->( @ret ) }, ); } =head2 kfoldl( \@items, \&body, $k ) CPS version of C, which collapses (or "folds") a list of values down to a single scalar, by successively accumulating values together. If C<@items> is empty, invokes C<$k> immediately, passing in C. If C<@items> contains a single value, invokes C<$k> immediately, passing in just that single value. Otherwise, initialises an accumulator variable with the first value in C<@items>, then for each additional item, invokes the C passing in the accumulator and the next item, storing back into the accumulator the value that C passed to its continuation. When the C<@items> are exhausted, it invokes C<$k>, passing in the final value of the accumulator. $body->( $acc, $item, $kret ) $kret->( $new_acc ) $k->( $final_acc ) Technically, this is not a true Scheme/Haskell-style C, as it does not take an initial value. (It is what Haskell calls C.) However, if such an initial value is required, this can be provided by kfoldl( [ $initial, @items ], \&body, $k ) =cut sub gkfoldl { my ( $gov, $items, $body, $k ) = @_; ref $items eq "ARRAY" or croak 'Expected $items as ARRAY ref'; ref $body eq "CODE" or croak 'Expected $body as CODE ref'; $k->( undef ), return if @$items == 0; $k->( $items->[0] ), return if @$items == 1; my $idx = 0; my $acc = $items->[$idx++]; gkloop( $gov, sub { my ( $knext, $klast ) = @_; goto &$klast unless $idx < scalar @$items; @_ = ( $acc, $items->[$idx++], sub { $acc = shift; goto &$knext } ); goto &$body; }, sub { $k->( $acc ) }, ); } =head2 kfoldr( \@items, \&body, $k ) A right-associative version of C. Where C starts with the first two elements in C<@items> and works forward, C starts with the last two and works backward. $body->( $item, $acc, $kret ) $kret->( $new_acc ) $k->( $final_acc ) As before, an initial value can be provided by modifying the C<@items> array, though note it has to be last this time: kfoldr( [ @items, $initial ], \&body, $k ) =cut sub gkfoldr { my ( $gov, $items, $body, $k ) = @_; ref $items eq "ARRAY" or croak 'Expected $items as ARRAY ref'; ref $body eq "CODE" or croak 'Expected $body as CODE ref'; $k->( undef ), return if @$items == 0; $k->( $items->[0] ), return if @$items == 1; my $idx = scalar(@$items) - 1; my $acc = $items->[$idx--]; gkloop( $gov, sub { my ( $knext, $klast ) = @_; goto &$klast if $idx < 0; @_ = ( $items->[$idx--], $acc, sub { $acc = shift; goto &$knext } ); goto &$body; }, sub { $k->( $acc ) }, ); } =head2 kunfold( $seed, \&body, $k ) An inverse operation to C; turns a single scalar into a list of items. Repeatedly calls the C code, capturing the values it returns, until it indicates the end of the loop, then invoke C<$k> with the collected values. $body->( $seed, $kmore, $kdone ) $kmore->( $new_seed, @items ) $kdone->( @items ) $k->( @all_items ) With each iteration, the C is invoked and passed the current C<$seed> value and two continuations, C<$kmore> and C<$kdone>. If C<$kmore> is invoked, the passed items, if any, are appended to the eventual result list. The C is then re-invoked with the new C<$seed> value. If C<$klast> is invoked, the passed items, if any, are appended to the return list, then the entire list is passed to C<$k>. =cut sub gkunfold { my ( $gov, $seed, $body, $k ) = @_; ref $body eq "CODE" or croak 'Expected $body as CODE ref'; my @ret; gkloop( $gov, sub { my ( $knext, $klast ) = @_; @_ = ( $seed, sub { $seed = shift; push @ret, @_; goto &$knext }, sub { push @ret, @_; goto &$klast }, ); goto &$body; }, sub { $k->( @ret ) }, ); } CPS::_governate "g$_" => $_ for @CPS_PRIMS; =head1 EXAMPLES The following aren't necessarily examples of code which would be found in real programs, but instead, demonstrations of how to use the above functions as ways of controlling program flow. Without dragging in large amount of detail on an asynchronous or event-driven framework, it is difficult to give a useful example of behaviour that CPS allows that couldn't be done just as easily without. Nevertheless, I hope the following examples will be useful to demonstrate use of the above functions, in a way which hints at their use in a real program. =head2 Implementing C using C use CPS::Functional qw( kfoldl ); my @words = qw( My message here ); kfoldl( \@words, sub { my ( $left, $right, $k ) = @_; $k->( "$left $right" ); }, sub { my ( $str ) = @_; print "Joined up words: $str\n"; } ); =head2 Implementing C using C The following program illustrates the way that C can split a string, in a reverse way to the way C can join it. use CPS::Functional qw( kunfold ); my $str = "My message here"; kunfold( $str, sub { my ( $s, $kmore, $kdone ) = @_; if( $s =~ s/^(.*?) // ) { return $kmore->( $s, $1 ); } else { return $kdone->( $s ); } }, sub { my @words = @_; print "Words in message:\n"; print "$_\n" for @words; } ); =head2 Generating Prime Numbers While the design of C is symmetric to C, the seed value doesn't have to be successively broken apart into pieces. Another valid use for it may be storing intermediate values in computation, such as in this example, storing a list of known primes, to help generate the next one: use CPS::Functional qw( kunfold ); kunfold( [ 2, 3 ], sub { my ( $vals, $kmore, $kdone ) = @_; return $kdone->() if @$vals >= 50; PRIME: for( my $n = $vals->[-1] + 2; ; $n += 2 ) { $n % $_ == 0 and next PRIME for @$vals; push @$vals, $n; return $kmore->( $vals, $n ); } }, sub { my @primes = ( 2, 3, @_ ); print "Primes are @primes\n"; } ); =head2 Forward-reading Program Flow One side benefit of the CPS control-flow methods which is unassociated with asynchronous operation, is that the flow of data reads in a more natural left-to-right direction, instead of the right-to-left flow in functional style. Compare sub square { $_ * $_ } sub add { $a + $b } print reduce( \&add, map( square, primes(10) ) ); (because C is a language builtin but C is a function with C<(&)> prototype, it has a different way to pass in the named functions) with my $ksquare = liftk { $_[0] * $_[0] }; my $kadd = liftk { $_[0] + $_[1] }; kprimes 10, sub { kmap \@_, $ksquare, sub { kfoldl \@_, $kadd, sub { print $_[0]; } } }; This translates roughly to a functional vs imperative way to describe the problem: Print the sum of the squares of the first 10 primes. Take the first 10 primes. Square them. Sum them. Print. Admittedly the closure creation somewhat clouds the point in this small example, but in a larger example, the real problem-solving logic would be larger, and stand out more clearly against the background boilerplate. =head1 SEE ALSO =over 4 =item * L - manage flow of control in Continuation-Passing Style =back =head1 AUTHOR Paul Evans =cut 0x55AA; CPS-0.19/lib/CPS/Governor.pm000444001750001750 524613470501137 14310 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2009-2012 -- leonerd@leonerd.org.uk package CPS::Governor; use strict; use warnings; use Carp; our $VERSION = '0.19'; =head1 NAME C - control the iteration of the C functions =head1 DESCRIPTION Objects based on this abstract class are used by the C variants of the L functions, to control their behavior. These objects are expected to provide a method, C, which the functions will use to re-invoke iterations of loops, and so on. By providing a different implementation of this method, governor objects can provide such behaviours as rate-limiting, asynchronisation or parallelism, and integration with event-based IO frameworks. =cut =head1 CONSTRUCTOR =cut =head2 $gov = CPS::Governor->new Must be called on a subclass which implements the C method. Returns a new instance of a governor object in that class. =cut sub new { my $class = shift; $class->can( "again" ) or croak "Expected to be class that can ->again"; return bless {}, $class; } # We're using this internally in gkpar() but not documenting it currently. # Details are still experimental. sub enter { my $self = shift; $self->again( @_ ); } =head1 SUBCLASS METHODS Because this is an abstract class, instances of it can only be constructed on a subclass which implements the following methods: =cut =head2 $gov->again( $code, @args ) Execute the function given in the C reference C<$code>, passing in the arguments C<@args>. If this is going to be executed immediately, it should be invoked using a tail-call directly by the C method, so that the stack does not grow arbitrarily. This can be achieved by, for example: @_ = @args; goto &$code; Alternatively, the L may be used to apply syntactic sugar, allowing you to write instead: use Sub::Call::Tail; ... tail $code->( @args ); =cut =head1 EXAMPLES =head2 A Governor With A Time Delay Consider the following subclass, which implements a C subclass that calls C between every invocation. package Governor::Sleep use base qw( CPS::Governor ); sub new { my $class = shift; my ( $delay ) = @_; my $self = $class->SUPER::new; $self->{delay} = $delay; return $self; } sub again { my $self = shift; my $code = shift; sleep $self->{delay}; # @args are still in @_ goto &$code; } =cut =head1 SEE ALSO =over 4 =item * L - Tail calls for subroutines and methods =back =head1 AUTHOR Paul Evans =cut 0x55AA; CPS-0.19/lib/CPS/Governor000755001750001750 013470501137 13606 5ustar00leoleo000000000000CPS-0.19/lib/CPS/Governor/Deferred.pm000444001750001750 1020213470501137 16034 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2009 -- leonerd@leonerd.org.uk package CPS::Governor::Deferred; use strict; use warnings; use base qw( CPS::Governor ); our $VERSION = '0.19'; =head1 NAME C - iterate at some later point =head1 SYNOPSIS use CPS qw( gkforeach ); use CPS::Governor::Deferred; my $gov = CPS::Governor::Deferred->new; gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "A$item "; goto &$knext; }, sub {}, ); gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "B$item "; goto &$knext; }, sub {}, ); $gov->flush; =head1 DESCRIPTION This L allows the functions using it to delay their iteration until some later point when the containing program invokes it. This allows two main advantages: =over 4 =item * CPU-intensive operations may be split apart and mixed with other IO operations =item * Multiple control functions may be executed in pseudo-parallel, interleaving iterations of each giving a kind of concurrency =back These are achieved by having the governor store a list of code references that need to be invoked, rather than invoking them immediately. These references can then be invoked later, perhaps by using an idle watcher in an event framework. Because each code reference hasn't yet been invoked by the time the C method is called, the original caller is free to store more pending references with the governor. This allows multiple control functions to be interleaved, as in the C and C example above. =cut =head1 CONSTRUCTOR =cut =head2 $gov = CPS::Governor::Deferred->new( %args ) Returns a new instance of a C object. Requires no parameters but may take any of the following to adjust its default behaviour: =over 8 =item defer_after => INT If given some positive number, C<$n> then the first C<$n-1> invocations of the C method will in fact be executed immediately. Thereafter they will be enqueued in the normal mechanism. This gives the effect that longrunning loops will be executed in batches of C<$n>. If not supplied then every invocation of C will use the queueing mechanism. =back =cut sub new { my $class = shift; my %args = @_; my $self = $class->SUPER::new( %args ); $self->{defer_after} = $args{defer_after} || 0; return $self; } sub again { my $self = shift; if( $self->{defer_after} and ++$self->{count} < $self->{defer_after} ) { my $code = shift; # args still in @_ goto &$code; } $self->later( @_ ); } sub later { my $self = shift; push @{ $self->{queue} }, [ @_ ]; } =head1 METHODS =cut =head2 $pending = $gov->is_pending Returns true if at least one code reference has been stored that hasn't yet been invoked. =cut sub is_pending { my $self = shift; return $self->{queue} && @{ $self->{queue} } > 0; } =head2 $gov->prod Invokes all of the currently-stored code references, in the order they were stored. If any new references are stored by these, they will not yet be invoked, but will be available for the next time this method is called. =cut sub prod { my $self = shift; $self->{count} = 0; my $queue = $self->{queue}; $self->{queue} = []; foreach my $item ( @$queue ) { my ( $code, @args ) = @$item; $code->( @args ); } } =head2 $gov->flush Repeatedly calls C until no more code references are pending. =cut sub flush { my $self = shift; $self->prod while $self->is_pending; } =head1 SUBCLASS METHODS The following methods are used internally to implement the functionality, which may be useful to implementors of subclasses. =cut =head2 $gov->later( $code, @args ) Used to enqueue the C<$code> ref to be invoked later with the given C<@args>, once it is determined this should be deferred (rather than being invoked immediately in the case of the first few invocations when C is set). =cut =head1 AUTHOR Paul Evans =cut 0x55AA; CPS-0.19/lib/CPS/Governor/Simple.pm000444001750001750 216213470501137 15533 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2009 -- leonerd@leonerd.org.uk package CPS::Governor::Simple; use strict; use warnings; use base qw( CPS::Governor ); our $VERSION = '0.19'; =head1 NAME C - iterate immediately as fast as possible =head1 SYNOPSIS use CPS qw( gkforeach ); use CPS::Governor::Simple; my $gov = CPS::Governor::Simple->new; gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "$item\n"; goto &$knext; }, sub {}, ); =head1 DESCRIPTION This L allows the functions using it to run as fast as possible. It invokes its continuations immediately using a tailcall, so as not to let the stack grow arbitrarily. Its constructor takes no special arguments, and it provides no other methods beyond those of C. =cut sub again { my $self = shift; my $code = shift; goto &$code; # intentionally leave @_ alone } =head1 AUTHOR Paul Evans =cut 0x55AA; CPS-0.19/t000755001750001750 013470501137 11055 5ustar00leoleo000000000000CPS-0.19/t/00use.t000444001750001750 33713470501137 12316 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use_ok( 'CPS' ); use_ok( 'CPS::Functional' ); use_ok( 'CPS::Governor' ); use_ok( 'CPS::Governor::Simple' ); use_ok( 'CPS::Governor::Deferred' ); done_testing; CPS-0.19/t/01kloop.t000444001750001750 217613470501137 12672 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kloop ); my $poke; my @nums; my $num = 1; kloop( sub { my ( $knext, $klast ) = @_; push @nums, $num; $num++; $poke = ( $num == 3 ) ? $klast : $knext; }, sub { push @nums, "finished"; }, ); is_deeply( \@nums, [ 1 ], 'kloop async - @nums initially' ); $poke->(); is_deeply( \@nums, [ 1, 2 ], 'kloop async - @nums after first poke' ); $poke->(); is_deeply( \@nums, [ 1, 2, "finished" ], 'kloop async - @nums after second poke' ); @nums = (); our $nested = 0; kloop( sub { my ( $knext, $klast ) = @_; is( $nested, 0, "kloop sync call does not nest for $num" ); local $nested = 1; push @nums, $num; $num++; ( ( $num == 5 ) ? $klast : $knext )->(); }, sub { push @nums, "finished"; }, ); is_deeply( \@nums, [ 3, 4, "finished" ], 'kloop sync - @nums initially' ); my @result; kloop( sub { my ( $knext, $klast ) = @_; $klast->( 1, 2, 3 ); }, sub { push @result, @_; } ); is_deeply( \@result, [], 'kloop clears @_ in $klast' ); done_testing; CPS-0.19/t/02kforeach.t000444001750001750 120613470501137 13322 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kforeach ); my @nums; kforeach( [ 1, 2, 3 ], sub { my ( $item, $knext ) = @_; push @nums, $item; $knext->(); }, sub { push @nums, "finished"; }, ); is_deeply( \@nums, [ 1, 2, 3, "finished" ], 'kforeach sync - @nums' ); @nums = (); kforeach( [ 4, 5, 6, 7 ], sub { my ( $item, $knext, $klast ) = @_; goto &$klast if $item == 6; push @nums, $item; $knext->(); }, sub { push @nums, "finished"; }, ); is_deeply( \@nums, [ 4, 5, "finished" ], 'kforeach sync - @nums' ); done_testing; CPS-0.19/t/03kdescend.t000444001750001750 112313470501137 13317 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kdescendd kdescendb ); my $ret; $ret = ""; kdescendd( [ [ [ 1, 2 ], 3, [ 4 ] ], 5 ], sub { my ( $i, $kmore ) = @_; return $kmore->( @$i ) if ref $i; $ret .= $i; $kmore->() }, sub { } ); is( $ret, "12345", 'kdescendd sync $ret' ); $ret = ""; kdescendb( [ [ [ 1, 2 ], 3, [ 4 ] ], 5 ], sub { my ( $i, $kmore ) = @_; return $kmore->( @$i ) if ref $i; $ret .= $i; $kmore->() }, sub { } ); is( $ret, "53124", 'kdescendb sync $ret' ); done_testing; CPS-0.19/t/04kpar.t000444001750001750 147613470501137 12510 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kpar ); my $result = ""; kpar( sub { $result .= "A"; shift->() }, sub { $result .= "B"; shift->() }, sub { $result .= "C"; } ); is( $result, "ABC", 'kpar sync' ); my @pokes; $result = ""; kpar( sub { $result .= "A"; push @pokes, shift }, sub { $result .= "B"; push @pokes, shift }, sub { $result .= "C"; } ); is( $result, "AB", 'kpar async before pokes' ); is( scalar @pokes, 2, '2 pokes queued' ); (shift @pokes)->(); is( $result, "AB", 'kpar async still unfinished after 1 poke' ); (shift @pokes)->(); is( $result, "ABC", 'kpar async now finished after 2 pokes' ); my @result; kpar( sub { shift->( 1, 2, 3 ); }, sub { push @result, @_; } ); is_deeply( \@result, [], 'kpar clears @_' ); done_testing; CPS-0.19/t/05kpareach.t000444001750001750 123013470501137 13316 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kpareach ); my $result = ""; kpareach( [ "A", "B" ], sub { $result .= shift; shift->() }, sub { $result .= "C"; } ); is( $result, "ABC", 'kpareach sync' ); my @pokes; $result = ""; kpareach( [ "A", "B" ], sub { $result .= shift; push @pokes, shift }, sub { $result .= "C"; } ); is( $result, "AB", 'kpareach async before pokes' ); is( scalar @pokes, 2, '2 pokes queued' ); (shift @pokes)->(); is( $result, "AB", 'kpareach async still unfinished after 1 poke' ); (shift @pokes)->(); is( $result, "ABC", 'kpareach async now finished after 2 pokes' ); done_testing; CPS-0.19/t/06kseq.t000444001750001750 125113470501137 12507 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kseq ); my $result = ""; kseq( sub { $result .= "A"; shift->() }, sub { $result .= "B"; shift->() }, sub { $result .= "C"; } ); is( $result, "ABC", 'kseq sync' ); my @pokes; $result = ""; kseq( sub { $result .= "A"; push @pokes, shift }, sub { $result .= "B"; push @pokes, shift }, sub { $result .= "C"; } ); is( $result, "A", 'kseq async before pokes' ); is( scalar @pokes, 1, '1 poke queued' ); (shift @pokes)->(); is( $result, "AB", 'kseq async still unfinished after 1 poke' ); (shift @pokes)->(); is( $result, "ABC", 'kseq async now finished after 2 pokes' ); done_testing; CPS-0.19/t/10liftk.t000444001750001750 124513470501137 12653 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( liftk ); my $kadd = liftk { shift() + shift() }; is( ref $kadd, "CODE", 'liftk returns plain CODE reference' ); my $sum; $kadd->( 1, 2, sub { $sum = shift } ); is( $sum, 3, 'liftk on BLOCK' ); sub mul { shift() * shift() }; my $kmul = liftk \&mul; my $product; $kmul->( 2, 3, sub { $product = shift } ); is( $product, 6, 'liftk on \&func' ); sub splitwords { split m/\s+/, $_[0] }; my $ksplitwords = liftk \&splitwords; my @words; $ksplitwords->( "my message here", sub { @words = @_ } ); is_deeply( \@words, [qw( my message here )], 'liftk works on list-returning functions' ); done_testing; CPS-0.19/t/11dropk.t000444001750001750 121513470501137 12657 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( dropk ); my $kadd = sub { $_[2]->( $_[0] + $_[1] ) }; my $add = dropk { } $kadd; is( ref $add, "CODE", 'dropk returns plain CODE reference' ); my $sum = $add->( 1, 2 ); is( $sum, 3, 'dropped function returns result' ); my $later; my $kwait = sub { my $k = pop; my @args = @_; $later = sub { $k->( @args ) } }; my $identity = dropk { $later->() } $kwait; my $result = $identity->( "hello" ); is( $result, "hello", 'idenity in scalar context' ); my @result = $identity->( 10, 20, 30 ); is_deeply( \@result, [ 10, 20, 30 ], 'identity in list context' ); done_testing; CPS-0.19/t/20governor-simple.t000444001750001750 123213470501137 14667 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS::Governor::Simple; my $gov = CPS::Governor::Simple->new; ok( defined $gov, 'defined $gov' ); isa_ok( $gov, "CPS::Governor", '$gov' ); my $called = 0; $gov->again( sub { $called = 1 } ); is( $called, 1, '$called is 1 after $gov->again' ); $gov->again( sub { $called = shift }, 3 ); is( $called, 3, '$called is 3 after $gov->again with arguments' ); my $poke; $gov->enter( sub { $called = 4; $poke = shift; }, sub { $called = 5 } ); is( $called, 4, '$called is 4 after $gov->enter storing kleave' ); $poke->(); is( $called, 5, '$called is 5 after invoking stored kleave' ); done_testing; CPS-0.19/t/21governor-deferred.t000444001750001750 254113470501137 15163 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS::Governor::Deferred; my $gov = CPS::Governor::Deferred->new; ok( defined $gov, 'defined $gov' ); isa_ok( $gov, "CPS::Governor", '$gov' ); ok( !$gov->is_pending, '$gov not yet pending' ); my $called = 0; $gov->again( sub { $called = 1 } ); ok( $gov->is_pending, '$gov now pending' ); is( $called, 0, '$called still 0' ); $gov->prod; ok( !$gov->is_pending, '$gov no longer pending after prod' ); is( $called, 1, '$called is 1 after prod' ); $gov->again( sub { $called = 2; $gov->again( sub { $called = 3; } ); } ); $gov->prod; ok( $gov->is_pending, '$gov is still pending after again-in-again' ); is( $called, 2, '$called is 2 after-in-again' ); $gov->prod; ok( !$gov->is_pending, '$gov no longer pending after inner again' ); is( $called, 3, '$called is 3 after inner again' ); $gov->again( sub { $called = 4; $gov->again( sub { $called = 5; } ); } ); $gov->flush; ok( !$gov->is_pending, '$gov no longer pending after flush' ); is( $called, 5, '$called is 5 after flush' ); $gov = CPS::Governor::Deferred->new( defer_after => 3 ); $called = 0; sub more { $called >= 6 and return; $called++; $gov->again( \&more ); } more(); is( $called, 3, '$called is 3 after first again' ); $gov->prod; is( $called, 6, '$called is 6 after poke' ); done_testing; CPS-0.19/t/30governor.t000444001750001750 66713470501137 13374 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( gkwhile gkforeach ); use CPS::Governor::Simple; my $gov = CPS::Governor::Simple->new; my $count = 0; gkwhile( $gov, sub { ++$count < 5 ? $_[0]->() : $_[1]->() }, sub {} ); is( $count, 5, '$count is 5 after gkwhile' ); $count = 0; gkforeach( $gov, [ 1 .. 5 ], sub { ++$count; $_[1]->() }, sub {} ); is( $count, 5, '$count is 5 after gkforeach' ); done_testing; CPS-0.19/t/31caller.t000444001750001750 410613470501137 13006 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kloop kforeach gkforeach ); eval { require Sub::Name } or plan skip_all => "No Sub::Name"; sub callers { my @pkgs; my $i = 1; push @pkgs, (caller $i)[3] and $i++ while (caller $i)[3]; @pkgs; } my $count = 0; my @callers; kloop( sub { my ( $knext, $klast ) = @_; push @callers, [ callers ]; ++$count == 3 ? $klast->() : $knext->(); }, sub {} ); is_deeply( \@callers, [ [ 'main::__ANON__', 'CPS::Governor::enter', 'CPS::gkloop' ], [ 'main::__ANON__', 'CPS::Governor::enter', 'CPS::gkloop' ], [ 'main::__ANON__', 'CPS::Governor::enter', 'CPS::gkloop' ], ], '@callers after kloop' ); @callers = (); kforeach( [ 1 .. 3 ], sub { my ( $i, $knext ) = @_; push @callers, [ callers ]; $knext->(); }, sub {} ); is_deeply( \@callers, [ [ 'main::__ANON__', 'CPS::Governor::enter', 'CPS::gkloop', 'CPS::gkforeach' ], [ 'main::__ANON__', 'CPS::Governor::enter', 'CPS::gkloop', 'CPS::gkforeach' ], [ 'main::__ANON__', 'CPS::Governor::enter', 'CPS::gkloop', 'CPS::gkforeach' ], ], '@callers after kforeach' ); my $gov = TestGovernor->new; @callers = (); gkforeach( $gov, [ 1 .. 3 ], sub { my ( $i, $knext ) = @_; push @callers, [ callers ]; $knext->(); }, sub {} ); $gov->poke while $gov->pending; is_deeply( \@callers, [ [ 'main::__ANON__', 'TestGovernor::poke' ], [ 'main::__ANON__', 'TestGovernor::poke' ], [ 'main::__ANON__', 'TestGovernor::poke' ], ], '@callers after gkforeach on deferred governor' ); done_testing; package TestGovernor; use base qw( CPS::Governor ); sub again { my $self = shift; my ( $code, @args ) = @_; $self->{code} = $code; $self->{args} = \@args; } sub pending { my $self = shift; return defined $self->{code}; } sub poke { my $self = shift; my $code = delete $self->{code} or die; $code->( @{ delete $self->{args} } ); } CPS-0.19/t/32leakcheck.t000444001750001750 165013470501137 13460 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS qw( kwhile ); if( $] < 5.008 ) { plan skip_all => "weaken() doesn't work before 5.8"; } my $destroycount = 0; my $poke; { my $obj = DestroyCounter->new( \$destroycount ); my $callcount = 0; kwhile( sub { my ( $knext, $klast ) = @_; $callcount++; # Just so this closure references the variable $obj = $obj; return $klast->() if $callcount == 3; $poke = $knext; }, sub { } ); } is( $destroycount, 0, 'Initially undestroyed' ); $poke->(); is( $destroycount, 0, 'Undestroyed after first poke' ); $poke->(); undef $poke; is( $destroycount, 1, 'Destroyed after second poke' ); done_testing; package DestroyCounter; sub new { my $class = shift; my ( $varref ) = @_; bless [ $varref ], $class; } sub DESTROY { my $self = shift; ${ $self->[0] }++; } CPS-0.19/t/40kmap.t000444001750001750 47413470501137 12460 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS::Functional qw( kmap ); my @nums; kmap( [ 1, 2, 3 ], sub { my ( $item, $k ) = @_; $k->( $item * 2 ); }, sub { @nums = @_; }, ); is_deeply( \@nums, [ 2, 4, 6 ], 'kmap sync - @nums' ); @nums = (); done_testing; CPS-0.19/t/41kgrep.t000444001750001750 50413470501137 12633 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS::Functional qw( kgrep ); my @nums; kgrep( [ 1, 2, 3, 4 ], sub { my ( $item, $k ) = @_; $k->( $item % 2 == 0 ); }, sub { @nums = @_; }, ); is_deeply( \@nums, [ 2, 4 ], 'kgrep sync - @nums' ); @nums = (); done_testing; CPS-0.19/t/42kfold.t000444001750001750 100713470501137 12642 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS::Functional qw( kfoldl kfoldr ); my $ret; kfoldl( [ 1, 2, 3 ], sub { my ( $left, $right, $k ) = @_; $k->( "($left+$right)" ); }, sub { $ret = shift; }, ); is( $ret, "((1+2)+3)", 'kfoldl sync - @nums' ); kfoldr( [ 1, 2, 3 ], sub { my ( $left, $right, $k ) = @_; $k->( "($left+$right)" ); }, sub { $ret = shift; }, ); is( $ret, "(1+(2+3))", 'kfoldr sync - @nums' ); done_testing; CPS-0.19/t/43kunfold.t000444001750001750 61213470501137 13167 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use CPS::Functional qw( kunfold ); my @nums; kunfold( 1, sub { my ( $n, $kmore, $kdone ) = @_; if( $n < 5 ) { $kmore->( $n + 1, $n ); } else { $kdone->(); } }, sub { @nums = @_; } ); is_deeply( \@nums, [ 1, 2, 3, 4 ], 'kunfold sync - @nums' ); done_testing; CPS-0.19/t/99pod.t000444001750001750 25713470501137 12327 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();