gdo*_*ald 6 hash proxy object perl6 raku
如何为哈希创建代理对象?我似乎找不到传递哈希键的方法:
#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;
Run Code Online (Sandbox Code Playgroud)
A Proxy是单个容器aka的替代Scalar。A Hash是一个复数容器,其中每个元素默认为a Scalar。
一个可能的解决方案(基于如何在Perl 6中为我的自定义类添加下标?)将实现的实现委派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}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |