djfdev
djfdev

Reputation: 6037

Updating list stored in hash table

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

Answers (1)

Óscar López
Óscar López

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.
  • The third parameter is an updater procedure which receives as a parameter the old value, in this case it's a procedure that conses a new item (because the old value was a list); this is set as the new value for the given key.
  • The last parameter is the default value to be returned in case the key was not found, before calling the updater procedure.

Upvotes: 2

Related Questions