Perl6: how to specify several requirements for a function parameter?

I have a special function that takes a list, each member of the list must satisfy several requirements. How to set this in perl6 function?

sub specialFunc(List $x) {}; (1) $x is a list # easy, List $x, but what about the following: (2) each member of $x is numeric (3) each member of $x is positive (4) each member of $x is greater than 7 (5) each member of $x is odd number (6) each member of $x is either the square or the cube of an even number plus 1; 

Thank you for your help!

lisprog

+5
source share
1 answer

A system such as Perl 6 is not flexible enough to declare such restrictions declaratively, but you can add a where clause to your parameter to check incoming arguments for a user expression.

For clarity, I would measure the expression to test each number in 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 can go one step further and split 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 satisfy only odd numbers, but I'm not big in number theory, so I'm not sure.

+7
source

Source: https://habr.com/ru/post/1261093/


All Articles