在Perl6(一种多分派语言)中,您可以找出是否存在与名称匹配的方法。如果有,您将获得与该名称匹配的方法对象的列表:
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 );我也许可以做很多工作来实现这一点,但我是否遗漏了一些已经存在的东西?
发布于 2017-06-17 12:08:17
当我在这个问题上点击提交时,我有了这个想法,这似乎仍然是太多的工作。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;
};我不确定我是否喜欢这个答案。
https://stackoverflow.com/questions/44600619
复制相似问题