CPS::Functional(3pm)

πŸ“¦
version 0.19 Β· 7 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

✨ NAME ✨

CPS::Functional β€” functional utilities in Continuation-Passing Style πŸ’…

This is the User Contributed Perl Documentation page for it, bestie. Sit down, grab a boba, we're doing callbacks. πŸ§‹


🌸 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);
   },
);

okay so that's the whole vibe right there. fetch a bunch of URLs, hand each one off, collect the sizes, sum them at the end. no blocking, no drama, just continuations. 😌


πŸ¦‹ DESCRIPTION πŸ¦‹

So basically, this module hands you CPS versions of data-flow functionals β€” the ones you already know and love like Perl's map and grep. The twist? Function bodies get invoked and are expected to return data, and the functional itself manages all of that for you. πŸ’–

They're built on top of the control-flow functionals provided by the CPS module itself. So this is like the data-flow layer sitting pretty on top of the control-flow layer. iykyk. πŸ‘‘


πŸ’œ FUNCTIONS πŸ’œ

πŸ’« kmap( \@items, \&body, $k )

CPS version of perl's map statement, fr fr. It calls the body code once for each element in @items, capturing the list of values the body passes into its continuation. When the items are exhausted, $k is invoked and passed a list of all the collected values. slay. ✨

$body->( $item, $kret )
   $kret->( @items_out )

$k->( @all_items_out )

πŸ’« kgrep( \@items, \&body, $k )

CPS version of perl's grep statement. Calls the body code once for each element in @items, capturing those elements where the body's continuation was invoked with a true value. When the items are exhausted, $k is invoked and passed a list of the subset of @items which were selected. it's giving filter but make it CPS πŸŽ€

$body->( $item, $kret )
   $kret->( $select )

$k->( @chosen_items )

πŸ’« kfoldl( \@items, \&body, $k )

CPS version of List::Util::reduce, which collapses (or "folds") a list of values down to a single scalar, by successively accumulating values together. πŸŒ€

Here's the tea on how it behaves:

  • If @items is empty, it invokes $k immediately, passing in undef.
  • If @items contains a single value, it invokes $k immediately, passing in just that single value.
  • Otherwise, it initialises an accumulator variable with the first value in @items, then for each additional item, invokes the body passing in the accumulator and the next item, storing back into the accumulator the value that body passed to its continuation. When the @items are exhausted, it invokes $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 foldl, as it does not take an initial value. (It is what Haskell calls foldl1.) However, if such an initial value is required, this can be provided by:
kfoldl( [ $initial, @items ], \&body, $k )

πŸ’« kfoldr( \@items, \&body, $k )

A right-associative version of kfoldl(). Where kfoldl() starts with the first two elements in @items and works forward, kfoldr() starts with the last two and works backward. reverse girlies rise πŸ™ˆ

$body->( $item, $acc, $kret )
   $kret->( $new_acc )

$k->( $final_acc )

As before, an initial value can be provided by modifying the @items array, though note it has to be last this time:

kfoldr( [ @items, $initial ], \&body, $k )

πŸ’« kunfold( $seed, \&body, $k )

An inverse operation to kfoldl() β€” it turns a single scalar into a list of items. πŸ” It repeatedly calls the body code, capturing the values it returns, until it indicates the end of the loop, then invoke $k with the collected values.

$body->( $seed, $kmore, $kdone )
   $kmore->( $new_seed, @items )
   $kdone->( @items )

$k->( @all_items )

With each iteration, the body is invoked and passed the current $seed value and two continuations, $kmore and $kdone. If $kmore is invoked, the passed items, if any, are appended to the eventual result list. The body is then re-invoked with the new $seed value. If $klast is invoked, the passed items, if any, are appended to the return list, then the entire list is passed to $k.


🌈 EXAMPLES 🌈

Okay bestie, real talk: 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. πŸ’–

πŸ“ Implementing join() using kfoldl()

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";
   }
);

πŸ“ Implementing split() using kunfold()

The following program illustrates the way that kunfold() can split a string, in a reverse way to the way kfoldl() 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;
   }
);

πŸ“ Generating Prime Numbers

While the design of kunfold() is symmetric to kfoldl(), 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";
   }
);

πŸ“ 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 map is a language builtin but reduce is a function with (&) 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. πŸ’…


πŸ”₯ SEE ALSO πŸ”₯

  • CPS β€” manage flow of control in Continuation-Passing Style

πŸ‘‘ AUTHOR πŸ‘‘

Paul Evans <leonerd@leonerd.org.uk> β€” thank you for your service, king 🫢


and that's the whole page, bestie!! this one's perl v5.34.0, dated 2022-06-30, and it lives at CPS::Functional(3pm). go forth and pass those continuations πŸ’–βœ¨πŸŽ€πŸ¦‹πŸŒΈ

πŸ“¦ where this page comes from