Scala Pattern Matching with Sets

pattern-matching, scala

Solution

Well, `x:xs` means `x` of type `xs`, so it wouldn't work. But, alas, you can't pattern match sets, because sets do not have a defined order. Or, more pragmatically, because there's no extractor on `Set`.

You can always define your own, though:

object SetExtractor {
  def unapplySeq[T](s: Set[T]): Option[Seq[T]] = Some(s.toSeq)
}

For example:

scala> Set(1, 2, 3) match {
     |   case SetExtractor(x, xs @ _*) => println(s"x: $x\nxs: $xs")
     | }
x: 1
xs: ArrayBuffer(2, 3)

Problem

The following doesn't work. ``` object Foo { def union(s: Set[Int], t: Set[Int]): Set[Int] = t match { case isEmpty => s case (x:xs) => union(s + x, xs) case _ => throw new Error("bad input") } } ``` error: not found: type xs How can I pattern match over a set?

Original source