Reputation: 6037
I have an immutable hash table that contains a series of lists as values. I wrote a procedure so I could add an item to one of the lists, returning a new hash:
(define (update hash key item)
(hash-set hash
key
(cons item
(hash-ref hash key)))))
This seems to work fine, but feels awkward and verbose. Is there a built-in procedure that accomplishes this, or maybe a more idiomatic way of achieving the same thing?
Upvotes: 1
Views: 632
Reputation: 236170
This is as simple as it can get:
(define (update hash key item)
(hash-update hash key (curry cons item) '()))
Explanation:
hash-update
returns a new hash with an updated value for the given key - or you can use hash-update!
to modify the hash in-place.hash
and key
are self-explanatory.cons
es a new item (because the old value was a list); this is set as the new value for the given key.Upvotes: 2