typestar

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

  1. Set("Sicilian", "London", "Caro-Kann") keeps one copy of each opening, in no fixed order.
  2. studied("London") applies the set as a function from element to Boolean, which is the same question studied.contains("Benoni") asks by name.
  3. studied + "Benoni" and studied - "London" build new sets, then studied.union(opponent) gathers the elements of both and studied.intersect(opponent) keeps only the shared ones.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Collections, step 12 of 27 in Language basics.

← Previous Next →

Sets in other languages