Sorted-map equality

here:
https://clojure.org/guides/equality
it says that:

Two maps are equal if they have the same set of keys, and each key maps to equal values in each map. As with sets, maps are unordered and the sort order is not considered for sorted maps.

now…personally, i always!!! forget that order does not affect equality for a sorted-map / set … so, why is that?!

It was a design choice made by Rich Hickey that maps are fundamentally a set of keys, each mapped to a corresponding value, and maps that are not sorted can be equal to maps that do have a sort order defined for the keys.

I think that besides that decision, perhaps another reason is that for sorted maps (and sorted sets), it is possible to provide an arbitrary comparison function, and if you wanted to do equality of sorted maps/sets based upon their sort order, then you have to pick how to compare equality on the comparison functions. It is possible to do that using pointer/reference equality between functions, but then if you have two sorted maps/sets with two different implementations of <= (for example), they would be not-equal because the function pointers/references are different, even though their sort order is the same.

Caveat: I did not design Clojure, so any reason I give for “why” is my best guess. I do not have any authoritative reference to share with you that answers the question “Why did the designer of the language do it this way?”

Thinking for a few minutes more, I realize that it would not be necessary to compare the functions to each other – one could simply iterate through the two sorted maps in their currently sorted order and verify that the keys were in the same order as each other.

I think the first answer I gave is the more fundamental one – a design decision that the sorted-ness of a map is not a fundamental property of its value – only its set of keys and their corresponding values are.

2 Likes