球拍中的哈希表 [英] Hash table in Racket
问题描述
我是Racket的新手,我试图定义一个将对哈希表进行排序的函数sort-mail
.
I'm new to Racket and I'm trying to define a function sort-mail
that is gonna sort a hash table.
我有一些已定义的列表:
I've some defined lists:
(define test-dates
'("Sun, 10 Sep 2017 09:48:44 +0200"
"Wed, 13 Sep 2017 17:51:05 +0000"
"Sun, 10 Sep 2017 13:16:19 +0200"
"Tue, 17 Nov 2009 18:21:38 -0500"
"Wed, 13 Sep 2017 10:40:47 -0700"
"Thu, 14 Sep 2017 12:03:35 -0700"
"Wed, 18 Nov 2009 02:22:12 -0800"
"Sat, 09 Sep 2017 13:40:18 -0700"
"Tue, 26 Oct 2010 15:11:06 +0200"
"Tue, 17 Nov 2009 18:04:31 -0800"
"Mon, 17 Oct 2011 04:15:12 +0000"
"Sun, 16 Oct 2011 23:12:02 -0500"
"Mon, 11 Sep 2017 14:41:12 +0100"))
(define sorted-dates
'("Tue, 17 Nov 2009 18:04:31 -0800"
"Tue, 17 Nov 2009 18:21:38 -0500"
"Wed, 18 Nov 2009 02:22:12 -0800"
"Tue, 26 Oct 2010 15:11:06 +0200"
"Sun, 16 Oct 2011 23:12:02 -0500"
"Mon, 17 Oct 2011 04:15:12 +0000"
"Sat, 09 Sep 2017 13:40:18 -0700"
"Sun, 10 Sep 2017 09:48:44 +0200"
"Sun, 10 Sep 2017 13:16:19 +0200"
"Mon, 11 Sep 2017 14:41:12 +0100"
"Wed, 13 Sep 2017 10:40:47 -0700"
"Wed, 13 Sep 2017 17:51:05 +0000"
"Thu, 14 Sep 2017 12:03:35 -0700"))
该功能应该通过此测试.
The function is supposed to pass this test.
(module+ test
(define test-hashes (map (lambda (x) (hasheq 'Date x)) test-dates))
(define sorted-hashes (map (lambda (x) (hasheq 'Date x)) sorted-dates))
(check-equal? (sort-mail test-hashes) sorted-hashes))
那么,我该如何开始?我发现Racket中的哈希表非常困难.我考虑过使用sort
函数,但是它猜测它并没有使用哈希表作为参数.
So, how do I even start? I find hash tables in Racket very difficult. I thought of using the sort
function, but it guess it doesn't take a hash table as an argument.
推荐答案
哈希表本质上是排序的.通过设计,它们通过将唯一键映射到索引而允许(理论上)即时查找时间.因此,由于没有必要,因此没有排序机制可对哈希图起作用.如果您试图将键值对汇总到一个列表中,然后进行排序,那肯定是可能的.
Hash tables are inherently sorted. By design, they allow for (theoretically) instant lookup time by mapping a unique key to an index. So, there is no sorting mechanism to act on a hash-map as there is no need. If you are trying to aggregate the key value pairs into a list, and then sort, that is certainly possible.
hash-keys将返回表中的键列表. 哈希值将返回表中的值列表.
hash-keys will return a list of keys in the table. hash-values will return a list of values in the table.
这些列表可以排序.您还可以将每个列表的每个元素配对在一起(因此是键值对列表).请尝试以下操作:
These lists can be sorted. You can also pair each element of each list together, (so a list of key-value pairs). Try the following:
(define h (make-immutable-hash
(list (cons 1 2)
(cons 3 4)
(cons 5 6)
(cons 7 8))))
(define (pair-up key value)
(list key value))
(map pair-up (hash-keys h) (hash-values h))
; Alternative to above, where pair-up is essentially defined inside.
(map (lambda (key value) (list key value)) (hash-keys h) (hash-values h))
这篇关于球拍中的哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!