6

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;
halfer
  • 19,824
  • 17
  • 99
  • 186
lisprogtor
  • 5,677
  • 11
  • 17

1 Answers1

8

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.

smls
  • 5,738
  • 24
  • 29