Given drop function implemented with pattern matching, what is the result of the code execution?
def drop[A](l: List[A], n: Int): List[A] =
  if (n <= 0) l
  else
    l match {
      case Nil => Nil
      case Cons(_, t) => drop(t, n - 1)
    }

drop(List(1, 2, 3), 1)
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]
Explanation
During the first iteration, n == 1 and pattern matching is executed. List(1, 2, 3) is the same as Cons(1, Cons(2, Cons(3, Nil))), that’s why on matching Cons(_, t) following values are substituted: _ => 1, t => Cons(2, Cons(3, Nil)) and the function is called recursively with the following parameters: drop(Cons(2, Cons(3, Nil)), 0). On the second iteration, n == 0 and list in place of first parameter is returned, which is Cons(2, Cons(3, Nil)) == List(2, 3).

Source: Scala Exercises: functional data structures

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Scala
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты