3.5
Implement dropWhile, which removes elements from the List prefix as long as they match a predicate.
def dropWhile[A](l: List[A], f: A => Boolean): List[A]
Solution
def dropWhile[A](l: List[A], f: A => Boolean): List[A] = l match {
case Nil => Nil
case Cons(head, tail) if f(head) => dropWhile(tail, f)
case _ => l
}
Run
object Solution {
def main(args:Array[String]): Unit = {
import List._
println("dropWhile (x<=3) in List(1,2,3,4,5) = " +
dropWhile(List(1,2,3,4,5), (x:Int) => (x <= 3)))
println("dropWhile (x<0) in List(1,2,3,4,5) = " +
dropWhile(List(1,2,3,4,5), (x:Int) => (x < 0)))
println("dropWhile (x<=3) in List() = " +
dropWhile(List(), (x:Int) => (x <= 3)))
}
}
Output
dropWhile (x<=3) in List(1,2,3,4,5) = Cons(4,Cons(5,Nil))
dropWhile (x<0) in List(1,2,3,4,5) = Cons(1,Cons(2,Cons(3,Cons(4,Cons(5,Nil)))))
dropWhile (x<=3) in List() = Nil