Ninety-Nine Scala Problems

Listening to a few different podcasts (The Java Posse among them), I found out about Ninety-Nine Scala Problems. As the description on the site says, it is an adaptation of the original Ninety-Nine Prolog Problems. I find the idea very interesting and decided to give it a go.

In summary, this is a bunch of (sort-of) small problems to be solved. You can use them to improve your knowledge in a programming language – Scala in this case. I won’t pretend I know where this trend started, but whoever had this idea for the first time, kudos to you!

During the next (bunch of, a lot of, certainly not few) weeks I’ll go through the problems trying to solve them, and post my impressions here. Those impressions will most likely contain my solutions, so please bear that in mind if you intend to try to solve the problems yourself as well. Also, the page mentioned above with the problems has possible solutions available and I’ll mention them, with links to the originals.



To allow you to understand what that feels like, lets talk about the first problem, which is really easy.

The definition of the first problem says:

P01 (*) Find the last element of a list.
     scala> last(List(1, 1, 2, 3, 5, 8))
     res0: Int = 8

I came up with basically two solutions. One that is pretty obvious and ugly, using the size of the list:

def last(list: List[Any]): Any = {

The other solution used Pattern Matching to decompose the list, until we have only the last element:

def lastUsingCase(list: List[Any]): Any = list match {
  case x :: Nil => x
  case x :: list => lastUsingCase(list)
  case _ => Unit

Phil Gold”s solutions include one Pattern Matching version, which is a little more elegant than mine, and a version using a built in feature that gives direct access to the last element of the list (the last function). I didn’t know about this function, so I already learned something new from this whole 99 Problems thing =) You can find Phil Gold’s solutions for this problem here.

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

One Response to Ninety-Nine Scala Problems

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

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