gpt4 book ai didi

raku - perl6/乐库 : how to I restrict the values allowed in a variable?

转载 作者:行者123 更新时间:2023-12-04 10:46:23 24 4
gpt4 key购买 nike

Perl6/乐库

我想创建一个子,只允许将某些值传递给它。并且不传递允许的值将产生检查器错误(perl6 -c)。

我该怎么做呢?

非常感谢,
-T

嗨,雷夫,

在我的 WinPopUps 模块中,我使用了“where”方法,因为它一目了然地告诉用户允许的值是什么。我喜欢它!一切都与可维护性有关! (对了,下面是你创造的怪物!)

sub WinPopUp( Str $TitleStr, 
Str $MessageStr,
Str $Icons where * ~~ "Exclamation" |
"Warning" |
"Information" |
"Asterisk" |
"Question" |
"Stop" |
"Error" |
"Hand",
Str $Buttons where * ~~ "AbortRetryIgnore" |
"CancelTryAgainContinue" |
"Help" |
"Ok" |
"OkCancel" |
"RetryCancel" |
"YesNo" |
"YesNoCancel" )
is export( :WinPopUp ) {

感谢您的帮助!
-T

让我知道您是否想要整个模块以及在哪里发布

最佳答案

您可以简单地添加 where值的条件

sub foo( Int $binary where * ~~ 0|1 ) { ... }
where条件可以是任意代码块(甚至是我相信的子代码块)。

如果您多次需要条件,您可以创建 subset .
subset BinaryInt of Int where * ~~ 0|1;

然后在签名中使用它
sub foo( BinaryInt $binary ) { ... }

请注意,这不仅限于子程序签名。约束/条件无处不在
my BinaryInt $i = 0; 
$i++;
$i++;
# -> Type check failed in assignment to $i; expected BinaryInt but got Int (2)

您还可以拥有子集的子集:
subset FalseBinaryInt of BinaryInt where not *;
my FalseBinaryInt $i = 0;
$i++;
# -> Type check failed in assignment to $i; expected FalseBinaryInt but got Int (1)

编辑:JJ 是对的。在这种情况下,枚举很有用。这
sub WinPopUp( Str $TitleStr, 
Str $MessageStr,
MessageBoxIcons $Icons where * ~~ Exclamation |
Information |
...

与枚举配对
enum MessageBoxIcons is export {
Exclamation => 0x00000030,
Information => 0x00000040,
...
}

保护您免受随机拼写错误的影响,因为枚举成员是符号,如果您拼错一个,编译器会捕捉到它。此外,您不必查找要输入 MessageBoxW 的值。 (我假设这就是你正在做的事情)。

说到 MessageBoxW ,我会调用你的子 message-box (在 Raku 中,我们倾向于将 CamelCase 仅用于类和类型等)只是为了与 MessageBoxW 保持一致。

关于raku - perl6/乐库 : how to I restrict the values allowed in a variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59222421/

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