hashmaphashtableracketimmutability

Racket mutable hash to immutable hash


I am using the procedure hash-set to set a value in a hash?. It seems to require the hash to be immutable?. So far I could not find a better way to transform a mutable hash into an immutable hash than the following:

(make-immutable-hash (hash->list myhash))

The hash is some yaml, which I am reading from a file and the yaml module gives me a mutable hash. For example I have the following code:

(hash-set yaml-hash
                "content"
                (make-immutable-hash
                 (hash->list
                  (my-hash-map content-hash
                               (lambda (key value)
                                 (cons key
                                       (markdown-to-html value)))))))

Is there a better way to transform a mutable hash into an immutable one, for the purpose of updating it? Or should I go a different way?


Solution

  • If the hash is mutable to begin with, you can modify it directly using hash-set!:

    (hash-set! yaml-hash <key> <new-value>)
    

    The above will change the value of the hash in-place, whereas hash-set will return a new hash, which you'll have to store or reassign somewhere else.