Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map over values of a hash table (racket)

I want to map a function over the values in a hash table, like so:

(hash-map add1 (hash "apple" 1 "pear" 2))
=> #hash(("apple" . 2) ("pear" . 3))

Is there a library function to do this? It'd be good to have one that worked on immutable hashetables too.

I looked on PlaneT, but didn't see anything there.

Now, if this really doesn't exist, I'll go ahead and write it. What would the etiquette for getting this into racket? I just fork it on github and add it to the standard library (and the docs!) and submit a pull request? Or should I make it a planeT first, and then ask for it to be moved in? I'd like to help, but I just don't know what's the 'proper' way to go about it.

like image 733
Theo Belaire Avatar asked Jan 31 '13 18:01

Theo Belaire


People also ask

Are hash tables space efficient?

Open Addressing techniques are highly efficient in memory usage as elements are stored in the space already allocated for the hash table. No extra space is required.

Can hash tables store strings?

The hash function will compute the same index for all the strings and the strings will be stored in the hash table in the following format. As the index of all the strings is the same, you can create a list on that index and insert all the strings in that list.

Is Hashtable mutable in Java?

The answer is NO. If we make the keys mutable then the hashcode() of the key will no more be consistent over time which will cause lookup failure for that object from the data structure.

How useful are hash tables?

Hash tables let us implement things like phone books or dictionaries; in them, we store the association between a value (like a dictionary definition of the word "lamp") and its key (the word "lamp" itself). We can use hash tables to store, retrieve, and delete data uniquely based on their unique key.


1 Answers

There is a hash-map, but it returns a list [1]

You would have to write your own hash-map to do exactly what you want.

#lang racket

(define (new-hash-map f h)
  (make-immutable-hash (hash-map h (λ (k v) (cons k (f v))))))

(new-hash-map add1 (hash "apple" 1 "pear" 2))

; => '#hash(("pear" . 3) ("apple" . 2))

Another form you might be interested in is for/hash [2]:

#lang racket

(define (new-hash-map2 f h)
  (for/hash ([(k v) (in-hash h)]) (values k (f v))))

(new-hash-map2 add1 (hash "apple" 1 "pear" 2))

; => '#hash(("pear" . 3) ("apple" . 2))

If you feel that this functionality should be included with Racket, patches are most welcome! The best way to contribute is to fork on github and submit a pull request.

like image 133
stchang Avatar answered Dec 14 '22 18:12

stchang