gpt4 book ai didi

object - 哈希的代理对象?

转载 作者:行者123 更新时间:2023-12-04 14:53:40 26 4
gpt4 key购买 nike

如何为哈希创建代理对象?我似乎找不到传递哈希键的方法:

#sub attr() is rw {
sub attr($name) is rw {
my %hash;
Proxy.new(
FETCH => method (Str $name) { %hash«$name» },
STORE => method (Str $name, $value) { %hash«$name» = $value }
);
}

my $attr := attr();
$attr.bar = 'baz';
say $attr.bar;

最佳答案

一个 Proxy是单个容器 aka Scalar 的替代品.一个 Hash是复数容器,其中每个元素默认为 Scalar .

一种可能的解决方案(基于 How to add subscripts to my custom Class in Perl 6? )是委托(delegate) Associative 的实现到内部散列但覆盖 AT-KEY替换默认Scalar的方法与 Proxy :

class ProxyHash does Associative {

has %!hash handles
<EXISTS-KEY DELETE-KEY push iterator list kv keys values gist Str>;

multi method AT-KEY ($key) is rw {
my $element := %!hash{$key};
Proxy.new:
FETCH => method () { $element },
STORE => method ($value) { $element = $value }
}
}

my %hash is ProxyHash;
%hash<foo> = 42;
say %hash; # {foo => 42}

关于object - 哈希的代理对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58088825/

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