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. Example: 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 = { list(list.size-1) }
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.
Pingback: Scala Problem Number Three « JCranky's Blog!