Perl6中的类型转换

7
如果我有一个类型为Str的对象,并且我想将其强制转换为Int,那么我可以通过在Str对象上调用Int方法来实现这一点,如下所示:"100".Int。我认为我知道我可以这样做,因为https://docs.perl6.org/type/Str中的Str类型文档列出了Int方法。现在,为了将这个新创建的Int强制转换为Complex类型的对象,我尝试了以下强制转换:"100".Int.Complex,它起作用了:-)。所以没有问题。但是我无法弄清楚为什么它能工作。Int类型文档中没有列出Complex方法。https://docs.perl6.org/type/Int。我在ComplexStr类中找到了一个名为Complex的方法,但我不知道它是否与我的Int相关。所以问题是:上面的强制转换是如何工作的?Complex方法从哪里来的?我怎样才能在尝试之前知道我实际上可以在Int对象上调用它?
2个回答

12

这只是文档不完整的情况。

您可以通过在对象上调用.^methods来查找它支持的方法:

perl6 -e '$_>>.name.join(", ").say for 123.^methods.sort(*.name).rotor(5 => 0, :partial)'
ACCEPTS, Bool, Bridge, Capture, Complex
DUMP, FatRat, Int, Num, Numeric
Range, Rat, Real, Str, WHICH
abs, acos, acosec, acosech, acosh
acotan, acotanh, asec, asech, asin
asinh, atan, atan2, atanh, base
ceiling, chr, cis, conj, cos
cosec, cosech, cosh, cotan, cotanh
exp, expmod, floor, gist, is-prime
isNaN, log, log10, lsb, msb
narrow, new, perl, polymod, pred
rand, roots, round, sec, sech
sign, sin, sinh, sqrt, succ

同时,我提交了一个关于文档仓库的修改以添加缺失的方法。网站已经使用这个改动重新生成:https://docs.perl6.org/type/Int#(Real)_method_Complex


1
命令应该是perl6 -e '$_>>.name.join(", ").say for 123.^methods.sort(*.name).rotor(5 , :partial)',否则你会错过最后四个方法tan,tanh,truncate,unpolar。 - Pat

3

我更多的是提供评论而不是答案。我只熟悉Perl 5。

来自https://docs.perl6.org/type/Cool

Methods in Cool coerce the invocant to a more specific type, and then call the same method on that type. For example both Int and Str inherit from Cool, and calling method substr on an Int converts the integer to Str first.

123.substr(1, 1);   # '2', same as 123.Str.substr(1, 1)

看起来 123.substr(1, 1) 就像是更传统的记法中的 Cool(123).substr(1, 1),然后被重新写成了 Str(123).substr(1, 1),因为 Str 继承自 Cool(就像经典的 OOP 倒过来做一样)。

类似地,"100".Int.Complex 看起来就像是 Cool("100").Int.Complex -> Int("100").Complex -> 100.Complex -> Cool(100).Complex -> Complex(100)


在REPL中,123.WHAT返回(Int),而Int类型的文档清楚地说明可以调用Int上的子字符串例程,因为该例程是从Cool继承/提供的。因此,您提到的示例似乎以直接的方式被文档覆盖。然而,"100".WHAT返回(Str),而"100".Int返回预测的(Int),由Str类型的文档说明。但是,Int类型的文档没有列出Complex方法;Cool类型的文档也没有。因此,在100.Complex阶段我迷失了。 - ozzy
嗨@Ozzy - 我喜欢查看perl6文档中的类型图 - 这是来自ComplexStr的一个,但您可能希望从另一个点开始https://docs.perl6.org/type/ComplexStr#Type_Graph - librasteve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接