Sets in Scala
A set of studied chess openings, tested for membership and combined against a rival repertoire.
// a Set literal keeps one copy of each element, in no fixed order
val studied: Set[String] = Set("Sicilian", "London", "Caro-Kann")
// a Set is a function from element to Boolean, so applying it
// asks about membership exactly like contains does
val knowsLondon: Boolean = studied("London")
val knowsBenoni: Boolean = studied.contains("Benoni")
// + and - build new sets, and adding a duplicate changes nothing
val plusBenoni: Set[String] = studied + "Benoni"
val minusLondon: Set[String] = studied - "London"
val stillThree: Boolean = (studied + "London").size == 3
// union gathers the elements of both sets
val opponent: Set[String] = Set("London", "Bird", "Sicilian")
val eitherPlayer: Set[String] = studied.union(opponent)
// intersect keeps only the ones both sets have
val bothPlayers: Set[String] = studied.intersect(opponent)
How it works
Set("Sicilian", "London", "Caro-Kann")keeps one copy of each opening, in no fixed order.studied("London")applies the set as a function from element toBoolean, which is the same questionstudied.contains("Benoni")asks by name.studied + "Benoni"andstudied - "London"build new sets, thenstudied.union(opponent)gathers the elements of both andstudied.intersect(opponent)keeps only the shared ones.
Keywords and builtins used here
BooleanSetStringval
The run, in numbers
- Lines
- 19
- Characters to type
- 840
- Tokens
- 122
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 98 seconds.
Step 3 of 3 in Collections, step 12 of 27 in Language basics.