3.4
Generalize tail to the function drop, which removes the first n elements from a list. Note that this function takes time proportional only to the number of elements being dropped—we don’t need to make a copy of the entire List.
def drop[A](l: List[A], n: Int): List[A]
Solution
def drop[A](l: List[A], n: Int): List[A] = l match {
case Nil => Nil
case _ if n == 0 => l
case Cons(_, tail) => drop(tail, n-1)
}
Run
object Solution extends App {
import List._
println("drop List(1,2,3,4), 2: " + List.drop(List(1,2,3,4),2))
println("drop List(1), 0: " + List.drop(List(1),0))
println("drop List(1), 1: " + List.drop(List(1),1))
println("drop List(1), 10: " + List.drop(List(1),10))
println("drop List(), 10: " + List.drop(List(),1))
println("drop Nil, 1: " + List.drop(Nil,1))
}
Output
drop List(1,2,3,4), 2: Cons(3,Cons(4,Nil))
drop List(1), 0: Cons(1,Nil)
drop List(1), 1: Nil
drop List(1), 10: Nil
drop List(), 10: Nil
drop Nil, 1: Nil