What is the result of code execution?
def init[A](l: List[A]): List[A] =
  l match {
    case Nil => sys.error("init of empty list")
    case Cons(_, Nil) => Nil
    case Cons(h, t) => Cons(h, init(t))

init(List(1, 2, 3))
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]
List(1, 2, 3) can be represented as Cons(1, Cons(2, Cons(3, Nil))) and it matches the third expression of pattern matching with the following substitutions: h == 1, t == Cons(2, Cons(3, Nil)), so the function is called recursively, having: Cons(1, init(Cons(2, Cons(3, Nil)))). On the second iteration, init(Cons(2, Cons(3, Nil))) is executed and list matches the last expression with following substitution: h == 2, t == Cons(3, Nil), which results in following expressioN: Cons(2, init(Cons(3, Nil)). On the third iteration, init(Cons(3, Nil)) is called and the list matches Cons(_, Nil), which results in Nil. After putting results from all iterations together, having the next expression: Cons(1, Cons(2, Nil)) == List(1, 2)

Source: Scala Exercises: functional data structures

Follow CodeGalaxy

Mobile Beta

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