I have a special function that takes a list, each member of the list must satisfy multiple requirements. How do I set this up in a perl6 function?
sub specialFunc(List $x) {};
The Perl 6 type system is not flexible enough to express such constraints declaratively, but you can add a where
clause to your parameter to check incoming arguments against a custom expression.
For clarity, I'd factor out the expression for testing each number into a subset
:
subset SpecialNumber of Numeric where {
$_ > 7 # (3), (4)
&& $_ !%% 2 # (5), since "odd" implies "not even"
&& .narrow ~~ Int # (5), since "odd" implies "integer"
&& ($_ - 1) ** (1/2 | 1/3) %% 2 # (6)
}
sub specialFunc(List $x where .all ~~ SpecialNumber ) {
...
}
You could go one step further, and factor out the whole where
clause into a subset
:
subset SpecialList of List where .all ~~ SpecialNumber;
sub specialFunc(SpecialList $x) {
...
}
PS: I think your requirement (5) may be redundant, since requirement (6) seems to only satisfy odd numbers anyway, but I'm not big on number theory so I'm not sure.