2010-02-24

Scala 2.8 Showcase - Collections

I would like to present some of the new features of Scala 2.8 which is a 2.8.0 Beta 1 at the moment of writing of this article.

Instead of programming dummy code I decided to implement some methods of computing square roots - but don't worry, just the simple ones. You don't have to dive in maths to understand code samples - in fact, in this article I won't really touch the square root part (I might a bit in the following articles).

Scala Collections

The Scala Collections have been improved since the previous stable release.

There are three packages now, scala.collection.mutable (mutable collections), scala.collection.immutable (immutable collections), scala.collection.generic (generic collections). Almost all types of collections exist in all three forms (but not all of them; namely, there is no immutable Buffer, why would there be). The official Scala collections PDF document also presents this neat and informative diagram:

A bit of introduction

Now I'm going to show you a few code examples. These are nothing but simple calls of standard Scala collections methods with a bit of explanation. This is by no means a full list of methods; the list of available methods is way too long. Please refer to the official Scala collections PDF document for more information.

As I mentioned before, the program calculates the square root using two methods:

Bisecting intervals - continuous estimations until a satisfactory result is found; for instance, when looking for a square root of 30, you can start looking for the solution between 5 (5 * 5 = 25 < 30) and 6 (6 * 6 = 36 > 30)

Here the negative method is used as a predicate given to the filter method (defined for the Iterable trait) which, as you can guess, filters the collection according to the predicate and returns the result which here is caught in a set called dataOnlyPositive. The result is:

The first two calls demonstrate the subsetOf operation which checks whether the first set is a subset of the other.

The third call uses our curried function - because the exists operation accepts a predicate that expects only one parameter, we provide it one - the partial functionequalsNumber(9.0). In other words, equalsNumber(9.0)(x) is itself a function that expects one argument (x). To further clarify, see the code example: