Take a look at the implementation of the following function, select the correct result:
def someFunction[A](l: List[A], h: A): List[A] = l match {
  case Nil => sys.error("empty list")
  case Cons(_, t) => Cons(h, t)
}

someFunction(List(1, 2, 3), 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]
Explanation
This is possible implementation of setHead function.
List(1,2,3) can be represented as Cons(1, Cons(2, Cons(3, Nil))). It doesn’t match Nil. When matching against Cons(_, t) the following values are substituted: _ => 1, t => List(2, 3) == Cons(2, Cons(3, Nil)). h==3, therefore Cons(h, t) == Cons(3, Cons(2, Cons(3, Nil))) == List(3, 2, 3).

Source: Scala Exercises: functional data structures

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Scala
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты