将角色混合到可调用对象中

Mixing roles into callables

理论上可以mix in a role into an object in runtime。所以我试图用一个函数来做到这一点:

my &random-f = -> $arg  { "Just $arg" };

say random-f("boo");

role Argable {
    method argh() {
        self.CALL-ME( "argh" );
    }
}

&random-f does Argable;

say random-f.argh;

在角色中,我使用self来引用已经定义的函数,CALL-ME来实际调用角色中的函数。但是,这会导致以下错误:

Too few positionals passed; expected 1 argument but got 0
in block <unit> at self-call-me.p6 line 5

我真的不知道谁在期待 1 个参数。理论上,它应该是 CALL-ME 函数,但谁知道呢。消除 self. 会产生不同的错误:CALL-ME used at line 11。将 does Callable 添加到 Argable (在将 self 放回去之后)会导致相同的错误。这可以做到吗?知道怎么做吗?

您的代码中有两处不正确:

say random-f.argh;  # *call* random-f and then call .argh on the result

您想在 Callable 上调用 .argh,所以:

say &random-f.argh;

其次,您应该只能调用 self:您可以在 .argh 方法的签名中对此进行调整:

method argh(&self:) {

所以最终代码变成:

my &random-f = -> $arg  { "Just $arg" };

say random-f("boo");

role Argable {
    method argh(&self:) {
        self( "argh" );
    }
}

&random-f does Argable;

say &random-f.argh;