Search code examples
clojure

Calculating a SHA for a persistent data structure


Is there a library to calculate some sort of a SHA for persistent data structures?

(sha (pr-str <datastructure>)) does not work because sometimes the order of keys are not the same when printed.


Solution

  • While it isn't a cryptographic function, clojure.core/hash-unordered-coll will give you a consistent hash value as long as the collections have the same contents, and maybe you can leverage on that:

    user=> (hash-unordered-coll (sorted-map :b 2 :a 1))
    161871944
    user=> (hash-unordered-coll {:b 2, :a 1})
    161871944
    user=> (hash-unordered-coll [[:b 2] [:a 1]])
    161871944
    

    See https://clojuredocs.org/clojure.core/hash-unordered-coll