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 > 0)
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
dropWhile removes elements from the List prefix as long as they match a predicate.
On the first iteration, List(1, 2, 3), which is the same as Cons(1, Cons(2, Cons(3, Nil))) is matched against first expression, and f(h) == (1 > 0) == true, so that dropWhile is called again with the rest of the list. Since being applied to all elements, f(h) returns true, as they are positive, the process continues until the last part of the list is remaining, which is Nil. It doesn’t match Cons(h, t), but matches second expression, which returns the remaining list and results in Nil.

Source: Scala Exercises: functional data structures

Следи за CodeGalaxy

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

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