在 Perl 6 中使用带有对象键的哈希 [英] Using a hash with object keys in Perl 6

查看:33
本文介绍了在 Perl 6 中使用带有对象键的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个 Hash 使用非字符串键,在我的例子中是数组或列表.

I'm trying to make a Hash with non-string keys, in my case arrays or lists.

> my %sum := :{(1, 3, 5) => 9, (2, 4, 6) => 12}
{(1 3 5) => 9, (2 4 6) => 12}

现在,我不明白以下内容.

Now, I don't understand the following.

如何检索现有元素?

> %sum{(1, 3, 5)}
((Any) (Any) (Any))

> %sum{1, 3, 5}
((Any) (Any) (Any))

如何添加新元素?

> %sum{2, 4} = 6
(6 (Any))

推荐答案

Elizabeth 的回答是可靠的,但在创建该功能之前,我不明白为什么您不能创建 Key 类用作散列键,它将具有基于其值而不是其在内存中的位置的显式散列函数.这个散列函数用于列表中的放置和相等性测试,是.WHICH.这个函数必须返回一个 ObjAt 对象,它基本上只是一个字符串.

Elizabeth's answer is solid, but until that feature is created, I don't see why you can't create a Key class to use as the hash key, which will have an explicit hash function which is based on its values rather than its location in memory. This hash function, used for both placement in the list and equality testing, is .WHICH. This function must return an ObjAt object, which is basically just a string.

class Key does Positional {
  has Int @.list handles <elems AT-POS EXISTS-POS ASSIGN-POS BIND-POS push>;
  method new(*@list) { self.bless(:@list); }
  method WHICH() { ObjAt.new(@!list.join('|')); }
}

my %hsh{Key};
%hsh{Key.new(1, 3)} = 'result';
say %hsh{Key.new(1, 3)}; # output: result

请注意,我只允许密钥包含 Int.这是一种相当自信的简单方法,即没有元素的字符串值包含|"字符,尽管具有不同的元素,但它可以使两个键看起来相同.然而,这并没有针对顽皮的用户进行强化——4 而是角色 :: { method Str() { '|'} } 是一个字符串化为非法值的 Int .如果您递归地使用 .WHICH,您可以使代码更强大,但我将把它留作练习.

Note that I only allowed the key to contain Int. This is an easy way of being fairly confident no element's string value contains the '|' character, which could make two keys look the same despite having different elements. However, this is not hardened against naughty users--4 but role :: { method Str() { '|' } } is an Int that stringifies to the illegal value. You can make the code stronger if you use .WHICH recursively, but I'll leave that as an exercise.

这个 Key 类也比您严格需要的更高级.拥有一个 @.list 成员并定义 .WHICH 就足够了.我定义了 AT-POS 和朋友,所以 Key 可以被索引、推送到或以其他方式被视为 Array.

This Key class is also a little fancier than you strictly need. It would be enough to have a @.list member and define .WHICH. I defined AT-POS and friends so the Key can be indexed, pushed to, and otherwise treated as an Array.

这篇关于在 Perl 6 中使用带有对象键的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆