Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
I'll provide some examples, but in order to appreciate them you must understand the library of tiny FP functions that form the core vocabulary of FP programming. I have enclosed a small subset of that vocabulary below, mostly drawn directly from the Haskell Prelude. I have tried to select examples that can be shown using only this subset.

Keep in mind that the following code is probably too small, too simple, and too limited to be useful for drawing general conclusions. The best you can hope for is to get a taste. To draw inferences about the whole cuisine from this tiny sampling would be a mistake.

First some library functions:

package ToolBox; use AutoCurry ':all'; use List::Util qw( min ); # zips sub zip { my $len = min( map scalar @$_, @_ ); map [ do { my $i=$_; map $_->[$i], @_ } ], 0..$len-1; } sub zip_with { my $f = shift; map $f->(@$_), zip(@_); } # folds & scans sub foldl { my $f = shift; my $z = shift; $z = $f->($z, $_) for @_; $z; } # (other folds and scans omitted) # functional glue: curry and compose sub _compose2 { my ($f, $g) = @_; sub { $f->($g->(@_)) } } sub compose { foldl( \&_compose2, @_ ); } sub pipeline { compose( reverse @_ ); } # a partially-applicable map sub map_c(&@) { my $f = shift; my $args = \@_; sub { map $f->($_), @$args, @_; } }

Now let us write code using the above vocabulary. First, the preliminaries:

use ToolBox; use Data::Dumper; # a convenience function for examining our output sub say(@) { local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; my @d = map Dumper($_), @_; print "@d$/"; }
Let us start with some simple functions to show the general idea:
# some simple binary operators sub plus { $_[0] + $_[1] } sub times { $_[0] * $_[1] } # build n-ary operators from them *sum = foldl_c( \&plus, 0 ); *product = foldl_c( \&times, 1 ); # test them out say sum(1..10); # 55 say product(1..10); # 3628800
Now let us build further to create a function to compute vector dot products:
*dot_product = compose( \&sum, zip_with_c( \&product )); say dot_product( [1,1,1], [1,2,3] ); # 6
So far, we have computed only with numbers. Let us now turn to data. One common programming task is to compute the combinations that can be generated by taking one element from a set of sets. (I selected this problem because various implementations can be found on Perl Monks for comparison.) Here's my implementation:
*combos = foldr_c( \&outer_prod, [[]] ); sub outer_prod { my ($xs, $ys) = @_; [ map do { my $x=$_; map [$x, @$_], @$ys }, @$xs ]; } say combos( ['a','b'], [1,2,3] ); # [['a',1],['a',2],['a',3],['b',1],['b',2],['b',3]]
Building further, let's compute power sets. One common method of computing the power set of a set S is the following:
  1. Replace each element e of S with the set {{e},{}}:
    [1,2] ==> [ [[1],[]], [[2],[]] ]
  2. Compute the combinations that can be formed from the sets:
          ==> [ [[1],[2]], [[1],[]], [[],[2]], [[],[]]] ]
  3. Compute the union of the sets within each combination:
          ==> [ [1,2], [1], [2], [] ]
This method translates directly into the following code:
*powerset = pipeline( map_c { [ [$_], [] ] }, # step 1 \&combos, # step 2 map_c { map [ map @$_, @$_ ], @$_ } # step 3 ); say powerset( 1, 2 ); # [1,2] [1] [2] [] say powerset(qw( a b c )); # ['a','b','c'] ['a','b'] ['a','c'] ['a'] # ['b','c'] ['b'] ['c'] []
Each step in the original method maps directly to a stage in the composition pipeline, the output of each stage becoming the input of the next.

This ends my example.

You are welcome to code your own versions of these functions for comparison. Because these functions are so simple, the comparisons might not yield much insight. A more useful exercise might be for you to write FP and non-FP code to solve more complex problems and then compare the coding experiences instead of the code itself.

Cheers,
Tom


In reply to Re^18: Near-free function currying in Perl by tmoertel
in thread Near-free function currying in Perl by tmoertel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (8)
    As of 2020-09-22 08:35 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      If at first I donít succeed, I Ö










      Results (128 votes). Check out past polls.

      Notices?