Tuesday, December 1, 2015

Perl6: comb, map and more arrays


   my @foo = <A B C D>;
   say @foo[2]; # hey, sigils don't "conjugate" anymore.
   say +@foo;      # count items in this array
   say +<A B C D>; # same thing



4

Next, map to apply a transform to each element of an array:

   say @foo.map( { $_ } )
   say <A B C D>.map( { $_ } )  # works with bare arrays too

A B C D
A B C D

   my $foo = 0;
   say <A B C D>.map( { 2 } )   
   say <A B C D>.map( { $foo++ } )

2 2 2 2
0 1 2 3


Now for some fun grep-like stuff: comb.

[http://doc.perl6.org/routine/comb] Searches for a regex in $input and returns a list of all matches (as Str by default, or as Match if $match is True), limited to at most $limit matches.

   my $in = 'ABCDABCDCBAABBDCC';
   say $in.comb( /A/ );      # find all A's
   say $in.comb( /A/, 2 );   # find at most 2 A's

A A A A
A A

   say +$in.comb( /A/ );     # count A's
   say +$in.comb( /B/ );     # count B's
   say +$in.comb( /C/ );     # count C's
   say +$in.comb( /D/ );     # count D's


5
5
3


 It sure would be nice to roll those last four statements together.  Here's one way:
  
   for <A B C D> -> $letter 
   { 
      say +$in.comb( /$letter/ ) 
   }


5
5
3


Slightly terser:

   for <A B C D> { say +$in.comb( /$_/ ) }


5
5
3

Or, using map:

   say <A B C D>.map( { +$in.comb( /$_/ ) } );  

4 5 5 3

Pop Quiz: why did that last statement return its result on one line instead of four lines?

No comments:

Post a Comment