gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:45:09 26 4
gpt4 key购买 nike

在 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‽

最佳答案

您可以查询元对象

> 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

关于raku - 如何显示值的类型层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44255424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com