Blodybla
Blodybla

Reputation: 11

Sort the values in a hash table and extract key in scheme

I'm new to scheme and trying to get the edge on it. I have a hash table. I want to sort the values of the hash table and then use it retrieve the key of which has the least value. I have a selection sort code in place for a list. But I don't know how to sort the values in the hash map and then extract the key which has the lowest value. Can somone thow some snippet as to how I go about this. Here is what I have until now.

(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 ))
 )
)

Upvotes: 1

Views: 903

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

There's no need to sort the values, we can extract the minimum and then find the corresponding key. Here's an idiomatic way in Racket to retrieve the key corresponding to the minimum value in the hash table:

(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

For example:

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

Upvotes: 2

Related Questions