gpt4 book ai didi

raku - 如何将具有关联作用的类哈希对象传递给期望哈希的构造函数?

转载 作者:行者123 更新时间:2023-12-04 14:22:11 24 4
gpt4 key购买 nike

我正在尝试 customized hashes .以下是尝试为类似配置的哈希实现更简单的查找:

use v6;

class X::Config::KeyNotFound is Exception {
method message() {
"Key not found!";
}
}

# A hash that allows for nested lookup using a '.' to separate keys.
# (This means that keys themselves cannot contain a dot)
# For example:
#
# %h = Config.new(%(a => %(b => 1)));
# my $foo = %h<a.b>; # <-- $foo = 1
#
class Config does Associative[Cool,Str] {
has %.hash;

multi method AT-KEY ( ::?CLASS:D: $key) {
my @keys = $key.split('.');
my $value = %!hash;
for @keys -> $key {
if $value{$key}:exists {
$value = $value{$key};
}
else {
X::Config::KeyNotFound.new.throw;
}
}
$value;
}

multi method EXISTS-KEY (::?CLASS:D: $key) {
my @keys = $key.split('.');
my $value = %!hash;
for @keys -> $key {
if $value{$key}:exists {
$value = $value{$key};
}
else {
return False;
}
}
return True;
}

multi method DELETE-KEY (::?CLASS:D: $key) {
X::Assignment::RO.new.throw;
}

multi method ASSIGN-KEY (::?CLASS:D: $key, $new) {
X::Assignment::RO.new.throw;
}

multi method BIND-KEY (::?CLASS:D: $key, $new){
X::Assignment::RO.new.throw;
}
}

my %hash = a => %(aa => 2, ab => 3), b => 4;
my %cfg := Config.new( hash => %hash );

# A dummy class to illustrate the problem:
class MyTest {
has %.config;
}

# Now this code does not work:
MyTest.new(
config => %cfg,
);

输出是:
Odd number of elements found where hash initializer expected:
Only saw: Config.new(hash => {:a(${:aa(2), :ab(3)}), :b(4)})
in block <unit> at ./p.p6 line 70

(第 70 行是 MyTest.new( 行)

如果我将普通哈希传递给构造函数,则代码可以正常工作,例如使用 %hash而不是 %cfg :
MyTest.new(
config => %hash,
);

最佳答案

类(class)还需要做Iterable角色:

class Config does Associative[Cool,Str] does Iterable {
...
}

这需要 iterator方法来实现。在这种情况下,委托(delegate)给嵌套哈希的迭代器可能是最简单的:
method iterator() { %!hash.iterator }

这样,错误就解决了。 (默认 iterator 给出了一个迭代器,它是一个包含对象本身的 1 项序列,因此观察到了错误。)

迭代器是必需的,因为构造具有哈希属性的对象的语义是赋值,而不是绑定(bind)。当我们分配到一个哈希中时,我们得到一个 Iterator从我们分配的东西中,并对其进行迭代以获取要分配的值。如果您的期望具有约束力,我会提到这一点 - 也就是说, MyTest将引用 Config 的实例.为此,需要编写自定义 BUILDMyTest 中进行绑定(bind),或将其声明为 has $.config相反,这意味着它只会引用 Config实例,而不是将其中的值复制到新的哈希中。

关于raku - 如何将具有关联作用的类哈希对象传递给期望哈希的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557297/

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