首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何知道可以使用特定的签名调用Perl 6方法?

如何知道可以使用特定的签名调用Perl 6方法?
EN

Stack Overflow用户
提问于 2017-06-17 12:01:37
回答 1查看 134关注 0票数 3

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

代码语言:javascript
复制
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, *%_)

这很好,但是有很多工作要做。我更喜欢更简单的东西,比如:

代码语言:javascript
复制
 $object.can( 'foo', $signature );

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

EN

回答 1

Stack Overflow用户

发布于 2017-06-17 12:08:17

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

代码语言:javascript
复制
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;
    };

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44600619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档