Raku 有 Python 的 Union 类型吗?
在 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)
Raku 可能没有像 Python 那样的 Union 类型,但是 where
子句可以达到类似的效果:
sub test(\x where * ~~ Int | Str | Rat) {
say(x)
}
sub MAIN() {
test(1);
test('str');
test(3.1415926);
}
我想知道 Raku 是否有可能提供像 Python 一样的 Union 类型?
# vvvvvvvvvvvvvvvvvvvv - the Union type doesn't exist in Raku now.
sub test(Union[Int, Str, Rat] \x) {
say(x)
}
In Python, Python has Union type, which is convenient when a method can accept multi types:
from typing import Union
def test(x: Union[str,int,float,]):
print(x)
if __name__ == '__main__':
test(1)
test('str')
test(3.1415926)
Raku probably doesn't have Union type as Python, but a where
clause can achieve a similar effect:
sub test(\x where * ~~ Int | Str | Rat) {
say(x)
}
sub MAIN() {
test(1);
test('str');
test(3.1415926);
}
I wander if Raku have a possibility to provide the Union type as Python?
# vvvvvvvvvvvvvvvvvvvv - the Union type doesn't exist in Raku now.
sub test(Union[Int, Str, Rat] \x) {
say(x)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的答案(与您的第一个解决方案非常相似;)是:(
或者您可以在调用签名中放置一个
where
子句,就像您所拥有的那样)与Python相反:
所以 - raku 语法就是用来做你所要求的......当然,它是一种不同的语言,所以它用不同的语言来做 方式。
我个人认为,如果类型检查被破坏,类型化语言就会失败。在我看来,不总是强制执行的类型暗示是一种虚假的安慰毯。
从更广泛的角度来看,raku 还为 IntStr、RatStr、NumStr 和 ComplexStr 提供内置 Allomorph 类型 -因此您可以使用字符串和数学函数在混合模式下工作
My answer (which is very similar to your first solution ;) would be:
(or you can put a
where
clause in the call signature, as you have it)In contrast to Python:
So - the raku syntax is there to do what you ask ... sure, it's a different language so it does it in a different way.
Personally I think that a typed language should fail if type checks are breached. It seems to me that type hinting that is not always enforced is a false comfort blanket.
On a wider point, raku also offers built in Allomorph types for IntStr, RatStr, NumStr and ComplexStr - so you can work in a mixed mode using both string and math functions