CPS

 view release on metacpan or  search on metacpan

lib/CPS/Functional.pm  view on Meta::CPAN

            sub { $acc = shift; goto &$knext }
         );
         goto &$body;
      },
      sub { $k->( $acc ) },
   );
}

=head2 kunfold( $seed, \&body, $k )

An inverse operation to C<kfoldl()>; turns a single scalar into a list of
items. Repeatedly calls the C<body> 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<body> 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<body> 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<join()> using C<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";
    }
 );

=head2 Implementing C<split()> using C<kunfold()>

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

=head2 Generating Prime Numbers

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

=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<map> is a language builtin but C<reduce> 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<CPS> - manage flow of control in Continuation-Passing Style

=back

=head1 AUTHOR

Paul Evans <leonerd@leonerd.org.uk>

=cut

0x55AA;



( run in 1.126 second using v1.01-cache-2.11-cpan-39bf76dae61 )