Scala Examples: Difference between revisions

From Celeste@Hoppinglife
Jump to navigation Jump to search
Created page with "== Pattern Matching on Seq == <pre class="hljs"> def f(ints: Seq[Int]): String = ints match { case Seq() => "The Seq is empty !" case Seq(first) => s"The seq..."
 
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Pattern Matching on Seq ==
== Pattern Matching on Seq ==


<pre class="hljs">
<syntaxhighlight lang="scala">
 
def f(ints: Seq[Int]): String = ints match {
def f(ints: Seq[Int]): String = ints match {
   case Seq() =>
   case Seq() =>
Line 30: Line 31:
       "The seq didn't match any of the above, so it must be empty"
       "The seq didn't match any of the above, so it must be empty"
}
}
</pre>
 
</syntaxhighlight>
 
See [https://riptutorial.com/scala/example/3056/pattern-matching-on-a-seq#:~:text=In%20general%2C%20any%20form%20that,and%20can%20have%20unexpected%20results. here]

Latest revision as of 22:16, 7 June 2020

Pattern Matching on Seq

def f(ints: Seq[Int]): String = ints match {
  case Seq() =>
      "The Seq is empty !"
  case Seq(first) =>
      s"The seq has exactly one element : $first"
  case Seq(first, second) =>
      s"The seq has exactly two elements : $first, $second"
  case  s @ Seq(_, _, _) => 
      s"s is a Seq of length three and looks like ${s}"  // Note individual elements are not bound to their own names.
  case s: Seq[Int] if s.length == 4 =>
      s"s is a Seq of Ints of exactly length 4"  // Again, individual elements are not bound to their own names.
  case _ =>
      "No match was found!"
}

def f(ints: Seq[Int]): String = ints match {
  case Seq(first, second, tail @ _*) =>
      s"The seq has at least two elements : $first, $second. The rest of the Seq is $tail"
  case Seq(first, tail @ _*) =>
      s"The seq has at least one element : $first. The rest of the Seq is $tail"
  // alternative syntax
  // here of course this one will never match since it checks
  // for the same thing as the one above
  case first +: tail =>
      s"The seq has at least one element : $first. The rest of the Seq is $tail"
  case _ =>
      "The seq didn't match any of the above, so it must be empty"
}

See here