对哈希表中的值进行排序并在方案中提取密钥

时间:2014-10-13 23:31:39

标签: scheme hashtable racket

我是计划的新手,并试图获得优势。我有一个哈希表。我想对哈希表的值进行排序,然后使用它检索其键值最小的键。我有一个列表的选择排序代码。但我不知道如何对哈希映射中的值进行排序,然后提取具有最低值的键。我可以告诉你如何解决这个问题。这是我到现在为止所拥有的。

(define (dirs-last-modified list)
  (define ht (make-hash))
   (cond
    [(null? list) '()]
    [else (hash-set! (first list) (file-or-directory-modify-seconds (first list))) (dirs-last-modified (rest list))])
 )
(define (selection list) 
 (cond ( (null? list) '() )
     ( else (cons (smallest list (car list))     ; put the smallest element
                                           ; at the front of the 
                                           ; current list 
                  (selection (remove list (smallest list (car list)))))
                                           ; call selection on the list
                                           ; minus the smallest
                                           ; element
     )
  )
 )

(define (remove list A)                ; remove the first occurance of atom A from list
 (cond ( (null? list) '() )           
    ( (= (car list) A) (cdr list))    ; Match found! 
    (else (cons (car list)(remove (cdr list) A)))   ; keep searching
  )
 )

(define (smallest list A)             ; looks for the smallest element in the list
                               ; atom A is the current smallest
 (cond ( (null? list) A)
    ( (< (car list) A) (smallest (cdr list)(car list)))
    (else (smallest (cdr list) A ))
 )
)

1 个答案:

答案 0 :(得分:2)

没有必要对值进行排序,我们可以提取最小值然后找到相应的键。这是Racket中用于检索与哈希表中的最小值对应的键的惯用方法:

(define (key-min-value ht)
  (car                 ; extract the key of the minimum entry
   (argmin             ; find the minimum in the entry list
    cdr                ; using as criterion the value in each entry
    (hash->list ht)))) ; convert hash table into key-value list

例如:

(key-min-value '#hash((c . 3) (a . 1) (b . 2)))
=> 'a