che*_*nyf 10 python union raku
在Python中,Python有Union类型,当一个方法可以接受多种类型时,这很方便:
from typing import Union
def test(x: Union[str,int,float,]):
print(x)
if __name__ == '__main__':
test(1)
test('str')
test(3.1415926)
Run Code Online (Sandbox Code Playgroud)
Raku 可能没有 Python 那样的 Union 类型,但子句where可以达到类似的效果:
sub test(\x where * ~~ Int | Str | Rat) {
say(x)
}
sub MAIN() {
test(1);
test('str');
test(3.1415926);
}
Run Code Online (Sandbox Code Playgroud)
我想知道Raku是否有可能像Python一样提供Union类型?
# vvvvvvvvvvvvvvvvvvvv - the Union type doesn't exist in Raku now.
sub test(Union[Int, Str, Rat] \x) {
say(x)
}
Run Code Online (Sandbox Code Playgroud)
我的答案(与您的第一个解决方案非常相似;)是:
subset Union where Int | Rat | Str;
sub test(Union \x) {
say(x)
}
sub MAIN() {
test(1);
test('str');
test(pi);
}
Constraint type check failed in binding to parameter 'x';
expected Union but got Num (3.141592653589793e0)
Run Code Online (Sandbox Code Playgroud)
(或者您可以where在调用签名中添加一个子句,如您所拥有的那样)
与Python相比:
所以 - raku 语法可以做你要求的事情......当然,它是一种不同的语言,所以它以不同的方式来做。
我个人认为,如果类型检查被破坏,类型化语言就会失败。在我看来,不总是强制执行的类型暗示是一种虚假的安慰毯。
从更广泛的角度来看,raku 还为 IntStr、RatStr、NumStr 和 ComplexStr 提供内置Allomorph类型 - 因此您可以使用字符串和数学函数在混合模式下工作
| 归档时间: |
|
| 查看次数: |
294 次 |
| 最近记录: |