4 ms·
Not exactly. Typically, iterating over a set is generally not what's intended when someone designs a set structure. This in turn becomes a problem in some lan
by krinchan 10y ago
Not exactly. Typically, iterating over a set is generally not what's intended when someone designs a set structure. This in turn becomes a problem in some languages.
95% of the time it simply doesn't matter. I mean, people iterate over maps all the time in day-to-day stuff, which is also a lookup-oriented structure.
But the other 5% of the time people expect list like behavior or performance from a set and don't get it, they act like this is a totally new thing for them even though they've been programming for years. :-/
EDIT: To clarify, it's really hard to explain to some folks that sets are optimized to answer quickly if they contain an X and Lists are optimized to quickly let you do a thing across all elements. Sets just happen to give you values back most of the time, but the real question they're trying to answer is if you have previously placed a known value into the set. Returning the actual contents of the Set is not actually a requirement at the more abstract, theoretical level though most standard libraries provide that.
In some libraries, actually getting at the contents and iterating over a set is quite hard. I've seen highly optimized sets for massive data that doesn't actually store the item, but a highly optimized, almost range encoded version (hashes 0xabcd through 0xafaa are in the set) of the data.
Like I said, the distinction between a list that disallows duplicate entries and a set really doesn't show up until you get into some pretty large scale things that most programmers don't ever use.
However, I feel understanding the distinction and how trying to answer one question (Do you contain X?) can lead to design decisions that make answering another question (What are all the unique values out of the values I just added to you?) more difficult leads to better programmers. That is, if they have the skills to abstract the thought exercise and apply it to other situations.
- Roboprog 10y agoThanks for the follow up. I don't expect a particular order if I spin through the contents of a set, but it hadn't occurred to me how expensive it might be simply to get the sequence. This makes a good example of when "polymorphism" or "strategy patterns" are useful to swap in and out how you do some related things to fit what actually ended up happening in an app.