Examine the next Scala match expression. What will be the result of pattern matching of the list?
val x = List(1, 2, 3, 4, 5) match {
  case Cons(x, Cons(2, Cons(4, _))) => x
  case Nil => 42
  case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
  case Cons(h, t) => h + sum(t)
  case _ => 101
Assuming the following code is available for your reference
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
List(1, 2, 3, 4, 5) can be represented as Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, Nil))))). The first case that matches it is Cons(x, Cons(y, Cons(3, Cons(4, _)))), where x and y values are inferred respectively x = 1 and y = 2.

Source: Scala Exercises: functional data structures

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Scala
Зареєструйся Зараз
або Підпишись на майбутні тести