如何在 Perl 6 中向现有类添加方法? [英] How do you add a method to an existing class in Perl 6?
问题描述
Int 类有一个方法 is_prime
,所以我想通了,只是为了咯咯笑,我想为 Int
添加一些其他方法,用于我的一些从事数论工作的爱好项目.
The Int class has a method is_prime
, so I figured, just for giggles, I'd like to add some other methods to Int
for some of my hobby projects that do number theory stuff.
我以为我可以这样做:
class Int {
method is-even (Int:D $number ) returns Bool:D {
return False if $number % 2;
return True;
}
}
say 137.is-even;
但这不起作用:
===SORRY!===
P6opaque: must compose before allocating
我不知道这是否意味着我不能这样做,或者我做错了.
I don't know if this means that I can't do that or that I'm doing it incorrectly.
我可以轻松创建一个继承自 Int
的新类,但这不是我感兴趣的:
I could easily make a new class that inherits from Int
, but that's not what I'm interested in:
class MyInt is Int {
method is-even () returns Bool:D {
return False if self % 2;
return True;
}
}
my $n = MyInt.new(138);
say $n.is-even;
我不是在寻找变通方法或替代解决方案.
I'm not looking for workarounds or alternate solutions.
推荐答案
这里有语法糖 - augment
:
use MONKEY-TYPING;
augment class Int {
method is-even() returns Bool:D {
return False if self % 2;
return True;
}
}
增加一个类被认为是危险的,原因有两个:第一,远距离动作,第二,因为(据我所知),有可能出现未定义行为 去优化 因为它可能会使各种方法缓存处于无效状态.
Augmenting a class is considered dangerous for two reasons: First, action at a distance, and second, because (as far as I'm aware), there's potential for undefined behaviour deoptimization as it might leave various method caches in an invalid state.
因此,需要在允许使用之前提供 MONKEY-TYPING
编译指示.
Thus, the requirement for providing the MONKEY-TYPING
pragma before you're allowed to use it.
顺便说一下,is-even
可以更紧凑地写成 self %% 2
.
As an aside, note that is-even
could be written more compactly as self %% 2
.
这篇关于如何在 Perl 6 中向现有类添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!