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]
Explanation
dropWhile removes elements from the List prefix as long as they match a predicate.
On the first iteration, list is matched against first expression. Since List(1, 2, 3) == Cons(1, Cons(2, Cons(3, Nil))), the following values are substituted: h == 1, t == Cons(2, Cons(3, Nil)), f(h) == (1 > 2) == false, which results in false and matching goes to the next expression, which is matched against anything and the list itself is returned, which is List(1, 2, 3).

Source: Scala Exercises: functional data structures

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes