In Raku, how does one write the equivalent of Haskell's span
function?
In Haskell, given a predicate and a list, one can split the list into two parts:
For example, the Haskell expression …
span (< 10) [2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4]
… evaluates to …
([2,2,2,5,5,7],[13,9,6,2,20,4])
How does one write the Raku equivalent of Haskell's span
function?
Based on the answer of @chenyf, I developed the following span
subroutine (additional later update reflects negated predicate within span
required to remain faithful to the positive logic of Haskell's span
function ) …
sub span( &predicate, @numberList )
{
my &negatedPredicate = { ! &predicate($^x) } ;
my $idx = @numberList.first(&negatedPredicate):k ;
my @lst is Array[List] = @numberList[0..$idx-1], @numberList[$idx..*] ;
@lst ;
} # end sub span
sub MAIN()
{
my &myPredicate = { $_ <= 10 } ;
my @myNumberList is Array[Int] = [2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4] ;
my @result is Array[List] = span( &myPredicate, @myNumberList ) ;
say '@result is ...' ;
say @result ;
say '@result[0] is ...' ;
say @result[0] ;
say @result[0].WHAT ;
say '@result[1] is ...' ;
say @result[1] ;
say @result[1].WHAT ;
} # end sub MAIN
Program output is …
@result is ...
[(2 2 2 5 5 7) (13 9 6 2 20 4)]
@result[0] is ...
(2 2 2 5 5 7)
(List)
@result[1] is ...
(13 9 6 2 20 4)
(List)
Utilizing information posted to StackOverflow concerning Raku's Nil
, the following updated draft of subroutine span
is …
sub span( &predicate, @numberList )
{
my &negatedPredicate = { ! &predicate($^x) } ;
my $idx = @numberList.first( &negatedPredicate ):k ;
if Nil ~~ any($idx) { $idx = @numberList.elems ; }
my List $returnList = (@numberList[0..$idx-1], @numberList[$idx..*]) ;
$returnList ;
} # end sub span
sub MAIN()
{
say span( { $_ == 0 }, [2, 2, 5, 7, 4, 0] ) ; # (() (2 2 5 7 4 0))
say span( { $_ < 6 }, (2, 2, 5, 7, 4, 0) ) ; # ((2 2 5) (7 4 0))
say span( { $_ != 9 }, [2, 2, 5, 7, 4, 0] ) ; # ((2 2 5 7 4 0) ())
} # end sub MAIN
I use first
method and :k
adverb, like this:
my @num = [2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4];
my $idx = @num.first(* > 10):k;
@num[0..$idx-1], @num[$idx..*];
A completely naive take on this:
sub split_on(@arr, &pred) {
my @arr1;
my @arr2 = @arr;
loop {
if not &pred(@arr2.first) {
last;
}
push @arr1: @arr2.shift
}
(@arr1, @arr2);
}
Create a new @arr1
and copy the array into @arr2
. Loop, and if the predicate is not met for the first element in the array, it's the last time through. Otherwise, shift the first element off from @arr2
and push it onto @arr1
.
When testing this:
my @a = [2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4];
my @b = split_on @a, -> $x { $x < 10 };
say @b;
The output is:
[[2 2 2 5 5 7] [13 9 6 2 20 4]]
Only problem here is... what if the predicate isn't met ? Well, let's check if the list is empty or the predicate isn't met to terminate the loop.
sub split_on(@arr, &pred) {
my @arr1;
my @arr2 = @arr;
loop {
if !@arr2 || not &pred(@arr2.first) {
last;
}
push @arr1: @arr2.shift;
}
(@arr1, @arr2);
}
In his presentation 105 C++ Algorithms in 1 line* of Raku (*each) Daniel Sockwell discusses a function that almost answers your question. I've refactored it a bit to fit your question, but the changes are minor.
#| Return the index at which the list splits given a predicate.
sub partition-point(&p, @xs) {
my \zt = @xs.&{ $_ Z .skip };
my \mm = zt.map({ &p(.[0]) and !&p(.[1]) });
my \nn = mm <<&&>> @xs.keys;
return nn.first(?*)
}
#| Given a predicate p and a list xs, returns a tuple where first element is
#| longest prefix (possibly empty) of xs of elements that satisfy p and second
#| element is the remainder of the list.
sub span(&p, @xs) {
my \idx = partition-point &p, @xs;
idx.defined ?? (@xs[0..idx], @xs[idx^..*]) !! ([], @xs)
}
my @a = 2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4;
say span { $_ < 10 }, @a; #=> ((2 2 2 5 5 7) (13 9 6 2 20 4))
say span { $_ < 5 }, [6, 7, 8, 1, 2, 3]; #=> ([] [6 7 8 1 2 3])
So I figured I'd throw my version in because I thought that classify
could be helpful :
sub span( &predicate, @list ) {
@list
.classify({
state $f = True;
$f &&= &predicate($_);
$f.Int;
}){1,0}
.map( {$_ // []} )
}
The map
at the end is to handle the situation where either the predicate is never or always true.
Version 6.e of raku will sport the new 'snip' function:
use v6.e;
dd (^10).snip( < 5 );
#«((0, 1, 2, 3, 4), (5, 6, 7, 8, 9)).Seq»
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.