Scala Problem Number Two

Following with my take on the Scala 99 Problems that I started here, lets talk a little bit about the second one. Here is the problem definition, from the original page:

P02 (*) Find the last but one element of a list.
Example:

scala> penultimate(List(1, 1, 2, 3, 5, 8))
res0: Int = 5

This one is very similar to the last problem and has similar solutions as well. The first solution I tried was, again, an ugly one:

def penultimate[A](list: List[A]): A = {
  list(list.size-2)
}

Terrible, but works. The second solution is nicer, with pattern matching, as before. But this time I learned a little bit from Phil Gold’s solution for the first problem, so prettier it is:

def penultimateWithPatternMatching[A](list: List[A]): A = list match {
  case x :: y :: Nil => x
  case _ :: tail => penultimateWithPatternMatching(tail)
  case _ => throw new NoSuchElementException
}

You can find Phil Gold’s solution to this problem here. His simpler solution is a bit better than mine, so my mind expands a little bit and I learn =). Also, he plays with a generic finder – interesting to read, and more mind expanding happens.

Advertisement
This entry was posted in scala and tagged , , , , . Bookmark the permalink.

1 Response to Scala Problem Number Two

  1. Pingback: Scala Problem Number Three « JCranky's Blog!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s