Raku 有 Python 的联盟类型吗?

Does Raku has Python's Union type?

在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 是否有可能提供 Union 类型 Python?

#        vvvvvvvvvvvvvvvvvvvv - the Union type doesn't exist in Raku now.
sub test(Union[Int, Str, Rat] \x) {
    say(x)
}

我的答案(与您的第一个解决方案非常相似;)是:

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)

(或者您可以在调用签名中放置一个 where 子句,就像您拥有的那样)

对比Python:

  • 这是 raku 原生的,不依赖于像“typing”这样的包被导入
  • Python Union / SumTypes 用于静态提示,这对例如。 IDE
  • 这些类型在 Python 中未强制执行(根据@freshpaste 评论和此 ),在 raku 中检查它们并将在运行时失败

所以 - raku 语法可以满足您的要求...当然,它是一种不同的语言,所以它以不同的方式实现。

我个人认为,如果类型检查被破坏,类型化语言应该失败。在我看来,并不总是强制执行的类型提示是一种虚假的安慰。

更广泛地说,raku 还为 IntStr、RatStr、NumStr 和 ComplexStr 提供内置 Allomorph 类型 - 因此您可以使用字符串和数学函数在混合模式下工作