Categories
Tech

Scala Saturday – The Set.union Method

A defining property of mathematical set is that it contain no duplicates. Sometimes you need to combine two sets. But what if those sets contain some of the same elements, so that the combination would contain duplicates? No worries! That’s where Set.union comes in.

Journey from Mariabronn

The classic lineup of progressive rock band Kansas in the 1970s consisted of Steve Walsh, Kerry Livgren, Rich Williams, Robby Steinhardt, Dave Hope, and Phil Ehart. However, over the years, the lineup changed several times. Currently Kansas are Ronnie Platt, David Manion, Rich Williams, David Ragsdale, Billy Greer, and Phil Ehart.

You can represent these two lineups as sets:

val classicKansas = Set(
  "Walsh", "Livgren", "Williams",
  "Steinhardt", "Hope", "Ehart")
val currentKansas = Set(
  "Platt", "Manion", "Williams",
  "Ragsdale", "Greer", "Ehart")

Magnum Opus

What if the classic Kansas lineup got together with the current Kansas lineup for a reunion tour? How would the omnibus lineup look? Call the first set’s union method, and pass it the second set:

val totalKansas = classicKansas union currentKansas
// totalKansas: scala.collection.immutable.Set[String] =
//   Set(Ehart, Walsh, Steinhardt, Platt, Ragsdale,
//     Manion, Greer, Livgren, Hope, Williams)

Notice how the union of the two sets does not contain duplicates even though Ehart and Williams were in both lineups.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.