Thursday, 29 December 2011

SaveAs for Strings in Scala with "Pimp my library" pattern

Problem

Have you ever wanted to save a string to a file? Well, it's one of this things you don't want to do in 3 lines of code like this:
val f = new FileWriter("some/file/name.txt")
f.write("My string I want to save")
f.close()
I would rather see it like that:
"My string I want to save".saveAs("some/file/name.txt")

Solution

Luckily in Scala we can use "pimp my library" pattern. It uses implicits to convert String to RichString containing the saveAs method:

Monday, 26 December 2011

Matrix multiplication in Scala

First take with idiomatic scala(77ms):


Second take - replacing fors with whiles(63ms):


Third take - sum in a variable(55ms):
Multi-threaded with parallel collections(15ms): Multi-threaded with parallel collections idiomatic scala(32ms):

Sunday, 25 December 2011

Lazy prime numbers in Scala


The key to understanding this example is the #:: operator. It is very similar to :: for collections. The difference is that it doesn't evaluate the right hand side argument immediately. Instead it keeps it's reference as a function and evaluates it only when needed. The evaluation is deferred until the actual element is needed.

Alternative to try-catch in Scala

I just saw such a nice control abstraction in Scala, that I wanted to share it. The original idea comes from akka-samples, I just modified it slightly to be more generic.


In this example the otherwise block gets executed only if system throws ClosedChannelExeption, but I could easily imagine other control abstractions hiding different exception types.

Scala block gotcha

Do you know what this line of code is going to print?
List(1,2,3).map{println("Adding 2"); _+2}

My first answer would be: 3 times "Adding 2".

Lets see:
scala> List(1,2,3).map{println("Adding 2"); _+2}
Adding 2
res11: List[Int] = List(3, 4, 5)

Hmm, it prints "Adding 2" just once...
So what is really happening here?

The cue is in understanding what is the semantics of a block in Scala.

The map function on List expects a function Int => B. The block {println("Adding 2"); _+2} is not a function Int => B. It's just a block of code which gets evaluated and returns value of the last expression. In our case when the block gets evaluated it prints "Adding 2" and then it returns a function x => x+2 (shorter _+2). Then this function is called 3 times to map elements of the list.

What is the workaround?

We just need to make sure that println is in the body of the function, that we pass to map, i.e.
scala> List(1,2,3).map{x => println("Adding 2"); x+2}
Adding 2
Adding 2
Adding 2
res12: List[Int] = List(3, 4, 5)

Enjoy!

Context bounds for type parameters in Scala

I thought I knew all type parameter bounds until recently, when I discovered the context bounds.

Let's have a look at the example:
def sum[T](list: Seq[T])(implicit typeClass : AddTypeClass[T]) = {
    list.reduce(typeClass.add(_,_))
  }

There is nothing unusual in here. Function sum needs a typeclass to perform it's operation.

Now let's express the same using context bounds:
def sum[T: AddTypeClass](list: List[T]) = {
    val typeClass = implicitly[AddTypeClass[T]]
    list.reduce(typeClass.add(_,_))
  }

Expression [T: AddTypeClass] means: "for some T such that, there exists a type AddTypeClass[T]". This is called context bounds.
Now we just need to get hold of an instance of type AddTypeClass[T]. We can use the function implicitly from Predef.

The definition of implicitly is as follows:
def implicitly[T](implicit e: T) = e

Enjoy!

Scala Hello World

You are probably wondering how to write the first scala program. Let’s start with the simple application, which calculates the area of a square.

Runnable application

In order to create runnable application we need to define a singleton object containing a main method. Let’s call it Area. (We’ll talk about singleton objects later.)
package helloWorld
object Area{
  def main(args: Array[String]){
    var width = args(0).toDouble
    println("Area = " + width * width ) 
  }
}

Methods

Method definition always starts with the def keyword followed by method name and comma-separated list of parameters. Unlike in java, parameter name comes first, and is followed by the colon and the parameter type, i.e.
def main(args: Array[String]){ 
  ... 
}
Method main takes one parameter called args of type Array[String].

Scala has no primitive array type

Array[String] is a class similar to ArrayList in java. There is no concept of primitive array in scala.

Generic types use square brackets

Array[String] is just an Array class parameterized by the String type.

Variables

var width = args(0).toDouble
To declare a variable we need to use var keyword. Scala compiler infers (guesses) a type of the variable. In our example, scala figures out that width is a Double. If you want you can be explicit about the types:
var width : Double = args(0).toDouble

Random access with () operator

You probably noticed that we are accessing elements of the args class with () operator. Array implements a special method apply, which allows random access to its elements using () operator, i.e. args(0)

Predef

You might wonder where does the println come from. It is defined in the Predef singleton object and is automatically imported in every scala file.

No semicolons

Semicolons at the end of the line are optional.

Compiling and running scala program

To run scala program you will need a scala distribution. You can download it from www.scala-lang.org. You also need JDK (Java Development Kit). Then make sure that scalac and scala are on the path and run the following commands:
> mkdir out
> scalac Area.scala -d out
> scala -cp out helloWorld.Area 5
Area = 25.0

Scalac is similar to javac; it compiles our file Area.scala into out directory. Then we run scala virtual machine, which is nothing more than java virtual machine with scala standard library on the classpath.


Enjoy!