【问题标题】:perl6: how to specify multiple requirements for a parameter of a function?perl6:如何为函数的参数指定多个要求?
【发布时间】:2016-12-10 18:34:55
【问题描述】:

我有一个特殊的函数,它需要一个列表,列表的每个成员都必须满足多个要求。如何在 perl6 函数中进行设置?

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;

感谢您的帮助!!

lisprog

【问题讨论】:

    标签: parameters signature raku


    【解决方案1】:

    Perl 6 类型系统不够灵活,无法以声明方式表达此类约束,但您可以在参数中添加 where 子句,以根据自定义表达式检查传入参数。

    为了清楚起见,我会将用于测试每个数字的表达式分解为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 ) {
        ...
    }
    

    您可以更进一步,将整个where 子句分解为subset

    subset SpecialList of List where .all ~~ SpecialNumber;
    
    sub specialFunc(SpecialList $x) {
        ...
    }
    

    PS:我认为您的要求(5)可能是多余的,因为要求(6)似乎无论如何只能满足奇数,但我对数论并不了解所以我不确定。

    【讨论】:

    • 非常感谢,smls !!!我同意,(6)暗示(5)是多余的。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2011-05-03
    • 2023-01-10
    • 2012-05-11
    • 2014-01-27
    相关资源
    最近更新 更多