- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
How to use pattern matching with sets?
Tue, 2010-05-04, 23:06
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!"
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!"
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!"
>
>