Language-Functional
view release on metacpan or search on metacpan
Functional.pm view on Meta::CPAN
the capital R, so as not to clash with the Perl command 'reverse'.
You should not try to Reverse an infinite list. eg:
$x = Reverse([1..6]); # [6, 5, 4, 3, 2, 1]
In Haskell:
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
=cut
sub Reverse($) {
my $xs = shift;
return [reverse @{$xs}];
}
=item And xs
Returns true if all the elements in xs are true. Returns false
otherwise. Note the capital A, so as not to clash with the Perl
command 'and'. You should not try to And an infinite list (unless you
expect it to fail, as it will short-circuit). eg:
$x = And([1, 1, 1]); # 1
In Haskell:
and :: [Bool] -> Bool
and = foldr (&&) True
=cut
sub And($) {
my $xs = shift;
map {
return 0 if not $_;
} @{$xs};
return 1;
}
=item Or xs
Returns true if one of the elements in xs is true. Returns
false otherwise. Note the capital O, so as not to clash with
the Perl command 'or'. You may try to Or an infinite list
as it will short-circuit (unless you expect it to fail, that
is). eg:
$x = Or([0, 0, 1]); # 1
In Haskell:
or :: [Bool] -> Bool
or = foldr (||) False
=cut
sub Or($) {
my $xs = shift;
map {
return 1 if $_;
} @{$xs};
return 0;
}
=item any p xs
Returns true if one of p(each element of xs) are true. Returns
false otherwise. You should not try to And an infinite
list (unless you expect it to fail, as it will short-circuit).
eg:
$x = any { even(shift) } [1, 2, 3]; # 1
In Haskell:
any :: (a -> Bool) -> [a] -> Bool
any p = or . map p
=cut
sub any(&$) {
my($p, $xs) = @_;
my $n = 0;
my $size = $#{$xs};
while ($n <= $size) {
return 1 if $p->($xs->[$n]);
$n++;
}
if ($size == $Language::Functional::INFINITE
or $size == $Language::Functional::INFINITE - 1
) {
confess "Evaluating predicate on inifinite number of elements " .
"would never end!";
}
return 0;
}
=item all p xs
Returns true if all of the p(each element of xs) is true. Returns
false otherwise. You may try to Or an infinite list
as it will short-circuit (unless you expect it to fail, that
is). eg:
$x = all { odd(shift) } [1, 1, 3]; # 1
In Haskell:
all :: (a -> Bool) -> [a] -> Bool
all p = and . map p
=cut
sub all(&$) {
my($p, $xs) = @_;
( run in 0.452 second using v1.01-cache-2.11-cpan-5b529ec07f3 )