Somewhat surprisingly, the #rust API for working with sets pushes you towards a double negative: to test whether a set has an intersection, you do

!set_a.is_disjoint(&set_b);

I would have thought that it'd be better API design to implement a `has_intersection` method (or similar) which avoids the ! and "dis" double negative.

I wonder why they went this way?

(And, yeah, there would be ways to avoid the double negative, but all are pretty clunky)

Thinking about ^^^ a bit more, I think the *actual* problem with the API is that HashSet's intersection method ought to return another HashSet instead of an Intersection.

This is more semantically correct (The intersection of two sets is a set, not an iterable list).

Plus, it would mean that you could have code like

set_a.intersection(&set_b)
.is_empty()

instead of

set_a.intersection(&set_b)
.collect::<HashSet<_>()
.is_empty()

I know it's a minor difference, but still!

Follow

@codesections `Intersection` is a lazy iterator. If you look at its source, the `intersect` method does nothing but initialize it---it does no actual work until you request an element from it.

In addition to being lazy, this also requires no memory allocation, and no hashing. Collecting into a new HashSet requires both of those things: allocating memory to hold the new set, and then hashing the items for storage. This is expensive if you don't need that.

Sign in to participate in the conversation
Mike Gerwitz's Mastodon Instance

Mike Gerwitz's personal Mastodon instance