如何显示值的类型层次结构?

时间:2017-05-30 06:51:53

标签: perl6 mop

在Perl5和Moose中,线性isa 线性化isa 有助于理解类层次结构。

方法WHAT显示值的具体类型:

> 42.WHAT
(Int)

如何显示

之类的内容
> 42.hypothetical-type-hierarchy
(Int) ┬ is (Cool) ─ is (Any) ─ is (Mu)
      └ does (Real) ─ does (Numeric)

......可能还有每个消费角色的更多行?

编辑:有两个角色的例子

class Beta {}
role Delta {}
role Gamma does Delta {}
role Eta {}
role Zeta does Eta {}
role Epsilon does Zeta {}
class Alpha is Beta does Gamma does Epsilon {}

# (Alpha) ┬ is (Beta)
#         ├ does (Gamma) ─ does (Delta)
#         └ does (Epsilon) ─ does (Zeta) ─ does (Eta)

my $ai = Alpha.new
$ai.^mro        # ((Alpha) (Beta) (Any) (Mu))

$ai.^roles      # ((Epsilon) (Zeta) (Eta) (Gamma) (Delta))
                # flat list, not two-element list of a tuple and triple‽

1 个答案:

答案 0 :(得分:8)

您可以使用

查询元对象
> 42.^mro
((Int) (Cool) (Any) (Mu))

其中mro代表方法解析顺序

> 42.^roles
((Real) (Numeric))

您可以通过副词:local控制返回哪些角色(排除从父类继承的角色 - 仅在类上可用)和:!transitive(排除通过其他角色组成的角色 - 可在两个角色和类)。

以下内容可以帮助您入门:

my $depth = 0;
for Alpha.^mro {
    say "is {.^name}";
    (sub {
        ++$depth;
        for @_ {
            say '  ' x $depth ~ "does {.^name}";
            &?ROUTINE(.^roles(:!transitive)); # recursive call of anon sub
        }
        --$depth;
    })(.^roles(:local, :!transitive));
}

鉴于您的示例代码稍作修改

role Delta {}
role Gamma does Delta {}
role Eta {}
role Zeta does Eta {}
role Epsilon does Zeta {}
class Beta does Gamma {}
class Alpha is Beta does Gamma does Epsilon {}

它产生输出

is Alpha
  does Epsilon
    does Zeta
      does Eta
  does Gamma
    does Delta
is Beta
  does Gamma
    does Delta
is Any
is Mu