【问题标题】:How can I know that I can call a Perl 6 method that with a particular signature?我怎么知道我可以调用具有特定签名的 Perl 6 方法?
【发布时间】:2017-06-17 04:01:37
【问题描述】:

在 Perl 6(一种多分派语言)中,您可以找出是否存在与名称匹配的方法。如果有,您将获得与该名称匹配的 Method 对象列表:

class ParentClass {
    multi method foo (Str $s) { ... }
    }

class ChildClass is ParentClass {
    multi method foo (Int $n) { ... }
    multi method foo (Rat $r) { ... }
    }

my $object = ChildClass.new;

for $object.can( 'foo' )
    .flatmap( *.candidates )
    .unique -> $candidate {
    put join "\t",
        $candidate.package.^name,
        $candidate.name,
        $candidate.signature.perl;
    };


ParentClass foo :(ParentClass $: Str $s, *%_)
ChildClass  foo :(ChildClass $: Int $n, *%_)
ChildClass  foo :(ChildClass $: Rat $r, *%_)

这很好,但工作量很大。我宁愿有一些更简单的东西,例如:

 $object.can( 'foo', $signature );

我或许可以做很多工作来实现这一点,但我是否错过了一些已经存在的东西?

【问题讨论】:

    标签: signature raku


    【解决方案1】:

    当我在这个问题上点击提交时,我有了这个想法,但这似乎仍然需要太多的工作。 cando 方法可以测试Capture(签名的逆)。我可以 grep 匹配的那些:

    class ParentClass {
        multi method foo (Str $s) { ... }
        }
    
    class ChildClass is ParentClass {
        multi method foo (Int $n) { ... }
        multi method foo (Rat $r) { ... }
        }
    
    my $object = ChildClass.new;
    
    # invocant is the first thing for method captures
    my $capture = \( ChildClass, Str );
    
    for $object.can( 'foo' )
        .flatmap( *.candidates )
        .grep( *.cando: $capture )
        -> $candidate {
        put join "\t",
            $candidate.package.^name,
            $candidate.name,
            $candidate.signature.perl;
        };
    

    我不确定我是否喜欢这个答案。

    【讨论】:

    • 我认为.candidates 步骤是多余的,这似乎也有效:$object.can( $method ).grep( *.cando: $capture )。或者如果$capture 不包含调用者:$object.can( $method ).grep( *.cando: \( $object, |$capture ) );
    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2015-06-21
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多