Set: Each Value Once
The club wants to know who ran this weekend. Asha ran on both Saturday and Sunday, but she should appear once in the answer. When all you care about is whether something is in a group, not how often or in what order, you want a Set.
The rule
A Set keeps each value once and answers "is it in?" fast.
val members = Set("Asha", "Ben", "Chen")
members.contains("Ben") // true
members("Dara") // false: the same question as contains
val grown = members + "Dara" // Set(Asha, Ben, Chen, Dara)
val same = grown + "Asha" // no change: Asha is already in
val smaller = grown - "Ben" // Set(Asha, Chen, Dara)- Adding a value that is already present does nothing:
Set("Asha", "Ben", "Asha").sizeis 2. - Like List and Vector, the default Set is immutable, so
+and-return a new set. - Checking membership is fast even for a big set, because a Set is organised by the values themselves rather than by position.
- A Set has no positions. You cannot ask for "the second member", and you should not rely on the order in which a Set prints.
Sets shine when you compare groups:
val saturday = Set("Asha", "Chen", "Dara")
val sunday = Set("Chen", "Ben")
saturday intersect sunday // Set(Chen): ran on both days
saturday union sunday // Asha, Chen, Dara and Ben: ran at least once
saturday diff sunday // Set(Asha, Dara): Saturday onlyA quick way to remove duplicates from a list is toSet, but that also throws away the order. When order matters, call distinct on the list instead: List("Asha", "Ben", "Asha", "Chen").distinct is List(Asha, Ben, Chen), keeping first appearances.
The shortcut
Translate the question's wording straight into an operation: "both" → intersect; "either" or "at least once" → union; "this but not that" → diff; "is X in?" → contains.
Spot the wording
"Saturday but not Sunday" is the "this but not that" pattern.
Drills
Answer fast — trust the rule.
What is Set("Asha", "Ben", "Asha").size?
Which expression answers "who ran on both days?"
What is sunday diff saturday?
With members = Set("Asha", "Ben", "Chen"), what is members("Zed")?
Arrivals were List("Ben", "Asha", "Ben"). You need each name once, in arrival order. What do you use?
Remember
- A Set holds each value once and answers membership fast; it has no positions.
- Map the wording: both → intersect, at least once → union, this but not that → diff.
- Trap: relying on a Set's printed order; use
distincton a list when order matters.
