Category Archives: scala

The Anagram Puzzle in Scala

A few weeks ago, we had a coding dojo in Adaptworks. There, we decided to use Scala as the coding language, and the problem to be solved was the Anagram puzzle. Unfortunately we didn’t manage to solve the problem during the coding session, but I’m sure everyone learned a bit more about Scala, which is always the main goal =)

Now, of course I wanted to have this puzzle solved. So I finally used some spare time and coded a solution. My solution is not the best possible one by any means, but it works and was really fun to work on.

Before showing the solution, a brief explanation of the problem, translated from the description in portuguese:

Write a program that generates all possible anagrams of a given string.

For instance, the possible anagrams of "biro" are:

biro bior brio broi boir bori
ibro ibor irbo irob iobr iorb
rbio rboi ribo riob roib robi
obir obri oibr oirb orbi orib

I’m still trying to find better and more readable solutions, but for now the current one is as follows:

class Anagram {
  def anagrams(word: String): Set[String] = anagram(word).toSet

  def anagram(word: String): List[String] = {
    if (word.length == 1) {
      List(word)

    } else {
      var anagrams = ListBuffer[String]()
      0 to word.length-1 foreach { i =>
        anagrams ++= (anagram(without(i, word)) map (word.charAt(i) + _))
      }

      anagrams.toList
    }
  }

  def without(index: Int, word: String): String = new StringBuilder(word).deleteCharAt(index).toString
}

In summary, what I tried to do was combining the ‘current’ char with all combinations of the rest of the input string. I hope this makes sense while reading the code. The code works – I have some unit tests that we generated during the coding dojo plus a couple more tests I added afterwards. Yet, I’m not happy with the anagram ListBuffer… I guess this could be solved in a more elegant way. Ideas?

An extra curiosity. While looking into the Scala Docs API to find possible ways to solve the puzzle, I discovered a very handy function that can be called on strings (and other kinds of collections as well): permutations. It basically solves this puzzle in a single method call…


Scala Problem Number Five

From the Scala 99 Problems, the problem number five goes like this:

P05 (*) Reverse a list.
Example:

scala> reverse(List(1, 1, 2, 3, 5, 8))
res0: List[Int] = List(8, 5, 3, 2, 1, 1)

Starting with the obvious solution, using the API:

val list = List(1, 2, 3, 4)
list.reverse

Yes, the List API has a reverse function. Pretty handy =)

How about being more creative now? Like this:

def myReverse[A](list: List[A]): List[A] = list match {
  case head :: tail => myReverse(tail) :+ head
  case Nil => Nil
}

With pattern matching and recursion, the solution is pretty simple. We basically decompose the list, and rebuild it in the opposite order. The code is simple, but it can take a while to understand if you are not used to recursion. The pattern matching part shows how nicely we can decompose Lists in scala =)

Lets try a different solution now:

def myReverse[A](list: List[A]): List[A] = {
  var reversedList = List[A]()
  list.foreach(item => reversedList = item +: reversedList)
  reversedList
}

Here we take a more ‘traditional’ approach – its closer to what we would do in Java, but still more compact and readable. First we create a buffer list, and add each element of the original list to the beginning of the buffer. Finally, we return the reversed list.

You can find the original solution to the problem here. As always, I learned something more after reading the original solution – I always write my solution before reading that. What I found is that it is also possible to solve the problem in a pure functional way, with foldLeft (copied from the original solution):

def reverseFunctional[A](ls: List[A]): List[A] =
    ls.foldLeft(List[A]()) { (r, h) => h :: r }

This solution is probably the most difficult to get at first, but the best after you get used to this kind of ‘extreme’ functional stuff. Nice =)


About nulls and System Properties in Scala

In Scala, it is usually a good idea to avoid nulls in your code. Instead of that, it is recommended that you use the Option class. This is how it works: if the value you are working with is null, it is represented by None, otherwise, it is represented by Some(value). Both None and Some are subclasses of Option.

This allows you to write code that is much more expressive than having ‘if != null‘ all over the place. Also, it is much less likely that you will forget to verify for nullity. One way of leveraging an Option value is through pattern matching:

val myValue: Option[String] = Some("Hello")
myValue match {
  case Some(x) => println("my value is " + x)
  case None => println("nonthing found")
}

The Option class also offers some collection-like functions that allow for great readability as well. From the Scaladoc:

val name: Option[String] = request.getParameter("name")
val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
println(upper.getOrElse(""))

Notice how the code execute transformations and ‘if-like’ filtering, in a very clean way. After that, they try to use the value with the getOrElse function, which allows you to pass a default value to be used if the result from the previous line was None. Finally, if you REALLY want to use an if statement, you can call the isDefined function, which returns true if the value is Some, false otherwise.

Now lets talk about system properties. Lets face it: dealing with System Properties in Java is boring. You have to get each property you are interested in and have to verify if it is null or empty. After all the talk above, you probably are starting to guess where I’m heading, right?

Well, it is better than that. Scala encapsulates the system properties in a way we can leverage all the Option stuff explained above. Those properties are encapsulated in a class named SystemProperties and can be accessed by the object ‘sys.props‘. Try typing it into a scala console session to see for yourself.

Since it is a map, you can use any map function you can use with other maps. Also, you can add and get properties from this object, and they will be reflected in the actual System Properties – which means that your Java code should be able to read the properties as well, even if through more traditional means (i.e. System.getProperty). Printing all system properties is as simple as:

sys.props.foreach(println)

And you clearly could do something more clever and useful with those properties.

There are two functions available in the SystemProperties class that I want to cover here: get and getOrElse. The first one returns a property with a given name, in an Option. With this, you can now handle your property with all the Option goodness we talked about above. The second function, getOrElse, is basically a direct way of calling the same function you could call in an Option. For example, lets say you read a database configuration from the system properties, and want to fall back to a default configuration if the property is not found:

val dbURL = sys.props.getOrElse("myapp.database.url", "jdbc:postgresql://localhost:5432/mydb")

A lot better than reading the property and verifying if it exists ‘by hand‘, right?


Migrating a java project to scala

Hi everybody!

This time I wanted to bring something different about scala – so I decided to migrate a java project to this language. The chosen one is an open source test framework for the Web Objects framework (sorry for the double f* word there) called WOUnit.

Web Objects is a web application framework that is quite old, and is developed by Apple. I’m not the right person to talk about this framework, so I’m not going further than that. The point is that this framework has some specificities that could make writing pure JUnit tests more troublesome than it should be, and this is where WOUnit comes in.

This project is reasonably small, so its a good choice for our small experiment. I’ll talk about what I did bellow, you can take a look in the project in the link above, and in the changes I made in my fork.

The current changes consisted of the following steps:

  • added the scala plugin and scala library dependency to the project’s pom.xml file – more about the maven scala plugin here;
  • renamed the EOAssert.java file to EOAssert.scala;
  • rewrote the contents of the file to use scala sintax

It was not complicated at all. You can find the current version of the file here. And what have we gained with this?

First, the code is now more readable. Which one is easier to read, this:

public static Matcher<EOEnterpriseObject> canBeDeleted() {
    return new CanBeDeletedMatcher<EOEnterpriseObject>();
}

or this:

def canBeDeleted(): Matcher[EOEnterpriseObject] =
  new CanBeDeletedMatcher[EOEnterpriseObject]

Nice, isn’t it? This comes to a point made by Martin Odersky (creator of Scala), where he said that the most important information in a function / method declaration is it’s name. Makes sense.

Second, you might have noticed that something seems to be missing in the scala version above. The java version has a static method, which doesn’t exist in scala. Actually, it isn’t even needed. Our EOAssert in scala is an object, which means scala handles it internally as a singleton. This feels a lot more correct from an object orientation point of view than having static things all over the place. Yet, from Java, you access EOAssert’s methods exactly as before – which means I didn’t have to change ANYTHING in the EOAssert class usages throughout the project, and it kept compiling and the tests passing.

Also, please notice how we are mixing java and scala code seamlessly here. Any doubts you could use scala as part of just about ANY java project without major headaches?

One thing I’m not sure about how it is working right now are the javadocs. In the migration, I kept then exactly how they were, and I’m not sure how the scaladoc would be generated for then. Since EOAssert class is intended as a public API, this is an issue that must be taken into account.

In summary, I didn’t do too much here – it was just a small experiment on migration a java project to scala. I hope you liked it and perhaps felt that scala is really worth considering serious usage. I’m not sure if I’ll continue this migration, but if I do, I’ll have more posts about it.

EDIT:

about the scaladocs point, this link might help a little bit: http://lampsvn.epfl.ch/trac/scala-old/wiki/Scaladoc/AuthorDocs


Scala Problem Number Four

Lets solve now the problem number four, from the Scala 99 Problems. This one goes as follows:

P04 (*) Find the number of elements of a list.
Example:

scala> length(List(1, 1, 2, 3, 5, 8))
res0: Int = 6

Lets start with the ridiculously easy way: using the API:

  def length(list: List) = {
    list.size
  }

Now lets try a different approach, with pattern matching and recursion:

  def count(acc: Int, remaining: List[Any]): Int = remaining match {
    case Nil => acc
    case x :: tail => count(acc + 1, tail)
  }

  def length(list: List[Any]) = count(0, list)

The function count receives an accumulator and a list. If the list is empty, it simply returns the accumulator. Otherwise, it calls itself again, passing an augmented accumulator and the tail of the list. This means that the recursion goes on until the list has nothing more inside it. We are removing the list elements, one by one, and counting them.

One last possibility, before linking the original solution:

  def length(list: List[Any]) = {
    list.foldLeft(0) { (count, item) => count + 1 }
  }

Here we are using foldLeft to process each element of the list and count the elements. Usually, we would use the list items to do some calculation to be used in the final value returned by foldLeft, but since all we want is to count the list elements, we are ignoring the item and just increasing the count. Pretty simple.

If you want to take a look at the original solution for this problem, click here. Looking at this solution, it looks like I was using tail recursion above and didn’t notice. Also, its foldLeft version is more compact (but less didactic, I guess…). Finally, I didn’t consider the direct recursion possibility – probably because I was having fun trying to figure out the tail recursion version =)


Just Java 2011

Hi!

Its been a long time since I last posted about an event. So, to recover from the sadness, lets talk about Just Java 2011, a Java event that happened this last weekend here in São Paulo.

The event consisted of two days filled with three simultaneous talks almost the entire time. The first day was nice and, besides meeting some friends and acquaintances, I learned something about Digital TV (App Store for TV applications!), saw some discussions about cloud computing (GAE, AWS and Azzure) and other Java stuff. There was also a Scala presentation, by Alberto Souza, which was very nice.

Cloud computing discussion

Cloud computing discussion

Now, the second day was the most interesting for me. It started with a Java FX presentation by Roger Brinkley. In summary, now they have a java API to do Java FX stuff almost in release version. So is Java FX Script dead for real? I know its officially dead, but I find it a little sad, since the java code seemed a bit too verbose… Perhaps I should learn more about it before coming to conclusions.

Roger Brinkley talks about Java FX

Roger Brinkley talks about Java FX

Anyway… what followed was another Scala presentation… by me! =) It was the first time I presented at this kind of event, so regardless of being doing Scala talks at Globalcode for a while, I was a bit nervous. The audience seemed to like the talk, so I left feeling quite good. Thank you all who attended! If you are curious, I talked about Scala in general, covering basic ideas and features. Like always, I tried to make people want to learn more about the language. Hope it worked =)

I then proceeded to meet more people, and attend more Java talks. One worth mentioning is about EJB and a coffee machine. The presentation was done by Globalcode’s Vininius Senger, and was really energetic, as all his talks always are.

What he did was to control a power plug with an Arduino board, with a coffee machine plugged into that power plug. If I understood correctly, he had an application server installed in this laptop, where he had a Timer EJB. This EJB would be called through an web interface and schedule a time for activating the coffee machine. Finally, the timer would connect to the Arduino board (through bluetooth I think) and get the power plug activated, and thus the coffee machine turned on. Great Fun!

Vinicius and his coffee machine demostration

Vinicius and his coffee machine demostration

It was a great event. To finish, I would to thank the organizers for the opportunity to talk. I’m looking forward to the next event!


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 = {
  list(n)
}

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.


Scala at the guardian uk

Hi!

In the news this last week, there was some information regarding the usage of Scala by The Guardian, a UK newspaper, and one of the biggest on the planet. I was aware that they were using Scala internally, but it seems they are starting to use it more and more.

Graham Tackley, a developer at The Guardian, talked about that in this video: http://skillsmatter.com/podcast/scala/how-we-mostly-moved-from-java-to-scala – its really worth while seeing this, he talks about how The Guardian uses Scala, and of course talks a lot about Scala itself – so much that this could be a great introductory video for you if you don’t know Scala yet.

One of the most interesting things shown in the video is a search tool / API they created – with Scala – to allow people to search their articles. I loved it, and more so for being open. Take a look for yourself: http://explorer.content.guardianapis.com/#/search?format=json

Thats all for now, see you next time!


Matching a range of numbers in Scala

Hi everybody!

Yesterday I did a presentation about Scala at Globalcode. It was very nice, thank you all who attended!

Now, one of the things I liked the most was the final part when people started making questions. I must admit I didn’t have answers to some of them, and this post is about one of those.

The question was something like: “can I pattern match against a range of numbers, like, say, 1 to 10?”

The answer is yes, although with a little more code than I thought necessary – yet, the solution is simple. First, if we want to match a simple number, we could write something like this:

myNumber match {
  case 10 => println("a ten")
  case num: Int => println("a number")
  case _ => println("something else")
}

In terms of matching numbers, we have two cases here. In one of them, we match directly a ’10′. In the other, we match any number. But how do we match a range of numbers? By adding something extra in the ‘any number’ case:

myNumber match {
  case 10 => println("a ten")
  case num if 0 until 100 contains num => println("a number between 0 and 100")
  case _ => println("something else")
}

This ‘something extra’ is called a ‘guard’. Guards allow us to add more verifications to values we match. With this, we can have any kind of restriction in any matched value. Also, we could have a ‘case’ for numbers between 0 and 100, and another one for any other number, like this:

myNumber match {
  case 10 => println("a ten")
  case num if 0 until 100 contains num => println("a number between 0 and 100")
  case num: Int => println("a number")
  case _ => println("something else")
}

Finally, please mind the order of the cases. Notice how we go from the more specific numbers, to the broader matching. This is not optional. you cannot put the broader case before the other ones – the code won’t even compile. In summary, this won’t work:

myNumber match {
  case num: Int => println("a number")
  case 10 => println("a ten")
  case num if 0 until 100 contains num => println("a number between 0 and 100")
  case _ => println("something else")
}

Now lets talks about how this work. Like a lot of things in Scala, ’0 until 100′ is not a special construct. It is implemented as library – which means you could have implemented this yourself. The steps that the scala compiler has to take to make this magic happen is something similar to the following:

  • 0 is an Int, so the compiler tries to find an ‘until’ method in the Int class, but it doesn’t exist;
  • the compiler finds out that the ‘until’ method exists in the ‘RichInt’ class;
  • it would be perfect if 0 was a RichInt… so the compiler now searches for a way to transform an Int in a RichInt;
  • luckily, it finds this: ‘implicit def intWrapper (x: Int) : RichInt’ in the Predef object;
  • 0 is then wrapped in a RichInt, and the compiler calls its until method, with ’100′ as the parameter;
  • the ‘until’ call results in a Range object and the compiler calls its ‘contains’ method, passing ‘num’ as the parameter;
  • the result of ‘contains’ is a boolean, which will decide if the number matches or not which what we want.

That’s quite a lot of stuff happening, even though there is nothing too complex in there. To close, one more last bit of information. Predef is an object that contains a lot of helper implicit methods, which are in the classpath of any scala application by default. Very handy.

I would like to thank Henrique Prage, who was in the Scala presentation, and sent me this link this morning: http://stackoverflow.com/questions/1346127/can-a-range-be-matched-in-scala – it really helped me find out quickly the answer to this question =)


sbt and maven

A few months ago I talked about my first impressions about sbt (simple build tool) here. My conclusion at the time was that NetBeans + Maven combination would suit me better. This changed a little bit, so I’m revisiting this topic to explain why.

First, I explored sbt a little more. I certainly still have a lot to learn, but I found out one thing that is making a lot of difference: you can use a maven pom file to handle your dependencies. This is great for a few reasons:

  • you can leverage your existing knowledge of pom files;
  • I’m not comfortable (yet) with the sbt own way of handing dependencies;
  • you can use tools that doesn’t support sbt directly – actually I don’t know of any that does that.

Lets elaborate some more. First, lets say you have a project that already uses maven. The first point means you can just type ‘sbt’, create an sbt project, and the tool will be able use the pom.xml file as a source for the project dependencies configuration. You will just have to use the sbt command ‘update’ after each time you change the pom file – which is very reasonable.

Second, the way sbt handles dependencies. Code. Basically, you configure the dependencies in a scala file, that gets compiled with the rest of the project. I don’t find this bad nor good. For now, I don’t have a strong opinion about this – but its still not comfortable.

Finally, the third point means you can use, say, NetBeans, with its great maven support, while using sbt as well. For a small personal project I’m currently working on, this is being very useful. My current development setup consists of NetBeans as the IDE, with sbt running in a console window in the ‘~test’ state. Every time I hit save on a source file inside NetBeans, sbt gets it, compiles and runs the tests. Yet, because I’m using an IDE instead of simple a code editor, a have full source code completion – which is really nice.

Of course this doesn’t work perfectly all the time – NetBeans gets confused from time to time and you might have to ignore some editor warnings. Nothing too bad though.


Follow

Get every new post delivered to your Inbox.