What is the result of 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)
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 == 3 and pattern matching is executed. List(1, 2) is the same as Cons(1, Cons(2, Nil)) and during matching with Cons(_, t) the following values are substituted: _ => 1, t => Cons(2, Nil).
On the second iteration, n == 2 and pattern matching is executed again: Cons(2, Nil) matched against Cons(_, t) results in the following substitution: t == Nil. On the third iteration, n == 1 and on pattern matching, Nil is returned as a result of function execution.

Source: Scala Exercises: functional data structures

Слідкуй за CodeGalaxy

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

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