gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:02:47 28 4
gpt4 key购买 nike

我有一个接受列表的特殊函数,列表中的每个成员都必须满足多个要求。我如何在 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 :

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)似乎只能满足奇数,但我对数论并不了解,所以我不确定。

关于parameters - perl6 : how to specify multiple requirements for a parameter of a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078922/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com