This page is no longer maintained — Please continue to the home page at www.scala-lang.org

How to use pattern matching with sets?

1 reply
Jefferson Andrade
Joined: 2010-04-09,
User offline. Last seen 42 years 45 weeks ago.
Hello!
This is probably a silly question, but I googled it and didn't find an answer.
I basically would like to do something like this:
s1 match {  case EmptySet => {...} // base case   case x +: s2 => {...}  // for inductive case}
But this does not work, of course. So for now I'm doing
if (s1.isEmpty) {...} else {  val x = s1.head  val s2 = s1 - x   ...}
But it does not feels right.
Thanks in advance.
Jeff.

--
Knowledge is power.
Power corrupts.
Study hard.
Be evil.

"You question the worthiness of my Code? I should kill you where you stand!"

Jason Zaugg
Joined: 2009-05-18,
User offline. Last seen 38 weeks 5 days ago.
Re: How to use pattern matching with sets?

Pattern matching on unordered collections is error prone. I assume
that, for this reason, Set.unapplySeq doesn't exist.

You can explicitly convert the set to an ordered collection, Seq, and
then pattern match.

Set(3, 1, 2).toSeq match {
case Seq() => "empty"
case Seq(first, rest@_*) => "got some"
}

-jason

On Wed, May 5, 2010 at 12:06 AM, Jefferson Andrade wrote:
> Hello!
> This is probably a silly question, but I googled it and didn't find an
> answer.
> I basically would like to do something like this:
> s1 match {
>   case EmptySet => {...} // base case
>   case x +: s2 => {...}  // for inductive case
> }
> But this does not work, of course. So for now I'm doing
> if (s1.isEmpty) {...}
> else {
>   val x = s1.head
>   val s2 = s1 - x
>   ...
> }
> But it does not feels right.
> Thanks in advance.
> Jeff.
>
> --
> Knowledge is power.
> Power corrupts.
> Study hard.
> Be evil.
>
> "You question the worthiness of my Code? I should kill you where you stand!"
>
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland