"List:D:" 中的第二个冒号在 Perl 6 中是什么意思?
What does the second colon in "List:D:" mean in Perl 6?
在doc.perl6.org中,我见过很多这样的方法:
method sum(List:D: --> Numeric:D)
我知道 List:D
是定义的一种列表,但是 D
后面的冒号是什么意思(即 List:D:
中的第二个冒号)?
我在 S12-objects 中找到了一些解释:
=head2 Invocants
Declaration of the invocant is optional. You may always access the
current invocant using the keyword self
.
...
To mark an explicit invocant, just put a colon after it:
method doit ($x: $a, $b, $c) { ... }
不过没看懂,乍一看有点奇怪
默认方法的调用者为self
所以这两个是等价的:
method foo ( $a ){…}
method foo ( \self: $a ){…} # generates warning
因此将第一个示例扩展为
的缩写
method sum( List:D \self: --> Numeric:D ){…} # generates warning
基本上,如果您想为方法指定调用者(第一个参数)的类型,但只想使用 self
而不是指定新变量,那么您就可以这样写。
它使用 :
将调用者与其余参数分开的原因是为了简化不指定调用者或调用者类型的常见情况。
当您使用这样的基本类型约束定义子时:
sub testB (Str $b) { say $b; }
然后您可以使用相关类型的实际实例以及类型对象本身来调用它:
> testB("woo")
woo
> testB(Str)
(Str)
:D 是一个额外的类型约束,所以你只能传递一个 "defined" 实例:
sub testC (Str:D $c) { say $c; }
> testB(Str)
(Str)
> testC("hoo")
hoo
> testC(Str)
Parameter '$c' of routine 'testC' must be an object instance of type 'Str', not a type object of type 'Str'. Did you forget a '.new'?
in sub testC at <unknown file> line 1
in block <unit> at <unknown file> line 1
可以找到更多详细信息here
在doc.perl6.org中,我见过很多这样的方法:
method sum(List:D: --> Numeric:D)
我知道 List:D
是定义的一种列表,但是 D
后面的冒号是什么意思(即 List:D:
中的第二个冒号)?
我在 S12-objects 中找到了一些解释:
=head2 Invocants
Declaration of the invocant is optional. You may always access the current invocant using the keyword
self
. ... To mark an explicit invocant, just put a colon after it:method doit ($x: $a, $b, $c) { ... }
不过没看懂,乍一看有点奇怪
默认方法的调用者为self
所以这两个是等价的:
method foo ( $a ){…}
method foo ( \self: $a ){…} # generates warning
因此将第一个示例扩展为
的缩写method sum( List:D \self: --> Numeric:D ){…} # generates warning
基本上,如果您想为方法指定调用者(第一个参数)的类型,但只想使用 self
而不是指定新变量,那么您就可以这样写。
它使用 :
将调用者与其余参数分开的原因是为了简化不指定调用者或调用者类型的常见情况。
当您使用这样的基本类型约束定义子时:
sub testB (Str $b) { say $b; }
然后您可以使用相关类型的实际实例以及类型对象本身来调用它:
> testB("woo")
woo
> testB(Str)
(Str)
:D 是一个额外的类型约束,所以你只能传递一个 "defined" 实例:
sub testC (Str:D $c) { say $c; }
> testB(Str)
(Str)
> testC("hoo")
hoo
> testC(Str)
Parameter '$c' of routine 'testC' must be an object instance of type 'Str', not a type object of type 'Str'. Did you forget a '.new'?
in sub testC at <unknown file> line 1
in block <unit> at <unknown file> line 1
可以找到更多详细信息here