Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl6: how to specify multiple requirements for a parameter of a function?

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) {};

(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

like image 295
lisprogtor Avatar asked Dec 10 '16 18:12

lisprogtor


1 Answers

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.

like image 59
smls Avatar answered Nov 12 '22 10:11

smls