3.2
Implement the function tail for removing the first element of a List. Note that the function takes constant time. What are different choices you could make in your implementation if the List is Nil? We’ll return to this question in the next chapter.
Solution
def tail[A](l: List[A]): List[A] = l match {
case Nil => Nil
case Cons(head, tail) => tail
}
Run
object Solution extends App {
import List._
println("Tail List(1,2,3,4): " + List.tail(List(1,2,3,4)))
println("Tail List(1): " + List.tail(List(1)))
println("Tail List(): " + List.tail(List()))
println("Tail Nil: " + List.tail(Nil))
}
Output
Tail List(1,2,3,4): Cons(2,Cons(3,Cons(4,Nil)))
Tail List(1): Nil
Tail List(): Nil
Tail Nil: Nil