What is the result of code execution?
def dropWhile[A](l: List[A], f: A => Boolean): List[A] =
  l match {
    case Cons(h, t) if f(h) => dropWhile(t, f)
    case _ => l

dropWhile(List(1, 2, 3), (x: Int) => x < 2)
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]
dropWhile removes elements from the List prefix as long as they match a predicate.
On the first iteration, pattern matching is performed. List(1, 2, 3) is the same as Cons(1, Cons(2, Cons(3, Nil))) and when matching against Cons(h, t) the following values are substituted: h == 1, t == Cons(2, Cons(3, Nil)), f(h) == (1 < 2) == true. Since first expression of pattern matching is satisfied, the dropWhile is called again with following parameters: dropWhile(Cons(2, Cons(3, Nil)), (x: Int) => x < 2). On the second iteration, Cons(2, Cons(3, Nil)) is matched against Cons(h, t) with following substitution: h == 2, t == Cons(3, Nil), f(h) == (2 < 2) == false, so it’s not matching the first expression. The second expression is matched against everything else, which is list itself, l == Cons(2, Cons(3, Nil)) == List(2, 3)

Source: Scala Exercises: functional data structures

Слідкуй за CodeGalaxy

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

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