首页 文章

我怎么知道我可以调用具有特定签名的Perl 6方法?

提问于
浏览
3

在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 );

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

1 回答

  • 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;
        };
    

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

相关问题