Scala Problem Number Three

I almost forgot I started this ‘series’… Sorry!

Now, with some time at hand, lets look at the problem number three, from the Scala 99 Problems. Like problem number one and two, this one is about list manipulations. It says:

P03 (*) Find the Kth element of a list.
By convention, the first element in the list is element 0.Example:

scala> nth(2, List(1, 1, 2, 3, 5, 8))
res0: Int = 2
First, the obvious solution, taking advantage of the List API:
def nth[A](n: Int, list: List[A]): A = {
This is the kind of code you should be using. But we can try to be a little bit clever and solve the problem in a different way, to explore a little more the features of the scala language, pattern matching in this case:
def nth[A](n: Int, list: List[A]): A = list match {
  case x :: tail if n == 0 => x
  case x :: tail => nth(n-1, tail)
  case _ => throw new IllegalStateException("cannot find element n")

My algorithm here is probably not very interesting – but the pattern matching usage is the point. Its flexibility always impresses me!

Finally, take a look at the original solution here. It seems the solution is similar to mine, exception it takes care of invalid situations better than I am. Anyway, nice stuff.

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

Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s