参数 – perl6:如何为函数的参数指定多个要求?
发布时间:2020-12-16 06:28:22 所属栏目:大数据 来源:网络整理
导读:我有一个特殊的函数,它接受一个列表,列表的每个成员必须满足多个要求.如何在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 po
我有一个特殊的函数,它接受一个列表,列表的每个成员必须满足多个要求.如何在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 解决方法
Perl 6类型系统不够灵活,无法以声明方式表达此类约束,但您可以在参数中添加where子句,以根据自定义表达式检查传入参数.
为清楚起见,我将用于测试每个数字的表达式分解为一个子集: 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 SpecialList of List where .all ~~ SpecialNumber; sub specialFunc(SpecialList $x) { ... } PS:我认为你的要求(5)可能是多余的,因为要求(6)似乎只满足奇数,但我对数论并不大,所以我不确定. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |