Findig the 2nd last item in the list, please explain this solution

Viewed 2548
// But pattern matching also makes it easy.
  def penultimateRecursive[A](ls: List[A]): A = ls match {
    case h :: _ :: Nil => h
    case _ :: tail     => penultimateRecursive(tail)
    case _             => throw new NoSuchElementException
  }

Can someone comment what this is doing line by line?

Is the [A] a generic like in c# we would do ?

h doesn't seem to be defined?

I think the major part of the algo is the recursive call:

case _ :: tail     => penultimateRecursive(tail)

There doesnt' seem to be a check for 2 items in the list, and then taking the 1st item to get the 2nd last, confused!

4 Answers
Related