Why don't HashSets implement PartialOrd?

⚓ rust    📅 2025-05-15    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 46 days ago. The information described in this article may have changed.

It's not a problem since I can always just make a struct that gives me this functionality, but from a language design perspective, I am curious why HashSet doesn't implement PartialOrd. There is a very natural partial ordering on the collections of sets: the subset relation, which could be implemented as:

impl<T: Hash + Eq> PartialOrd for HashSet<T> {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        match self.len().cmp(&rhs.len()) {
            Ordering::Equal if self.iter().all(|t| rhs.contains(t)) => Some(Ordering::Equal),
            Ordering::Less if self.iter().all(|t| rhs.contains(t)) => Some(Ordering::Less),
            Ordering::Greater if rhs.iter().all(|t| self.contains(t)) => Some(Ordering::Greater),
            _ => None,
        }
    }
}

One could extend to the same idea to HashMap when the value type is PartialEq by replacing all(|t| rhs.contains(t)) with all(|(k, v)| rhs.get(k).is_some_and(|w| *w == *v)).

For even more flexibility, one could modify this for value types implementing PartialOrd by first comparing the underlying sets of keys and then performing a point-wise comparison of the values, but that might be getting too wild: in particular, it would conflict with the foregoing definition.

In any case, I'm just curious why the seemingly-natural definition of a partial order on sets is not part of std.

3 posts - 3 participants

Read full topic

🏷️ rust_feed