Raku有Python的Union类型吗?

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)

p6s*_*eve 7

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

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 原生的,不依赖于像“typing”这样的包来导入
  • Python Union / SumTypes 用于静态提示,这对于例如。IDE
  • 这些类型在 Python 中是未强制执行的(根据 @freshpaste 注释和此SO),在 raku 中它们会被检查并在运行时失败

所以 - raku 语法可以做你要求的事情......当然,它是一种不同的语言,所以它以不同的方式来做。

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

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