Scala Problem Number Six

From the Scala 99 Problems, lets face the problem number six:

P06 (*) Find out whether a list is a palindrome.
Example:

scala> isPalindrome(List(1, 2, 3, 2, 1))
res0: Boolean = true

The first thing I had to do was to find out the meaning of palindrome. From the example, it’s easy to guess, but I prefer to be sure. So, from dictionary.com:

1. a word, line, verse, number, sentence, etc., reading the same backward as forward, as Madam, I’m Adam  or Poor Dan is in a droop.

Interesting, so this is valid not only for numbers =)

Now, to some coding! My first solution:

def isPalindrome(list: List[Any]): Boolean = list match {
  case Nil => true
  case head :: Nil => true
  case head :: rest if head == rest.last => isPalindrome(rest.dropRight(1))
  case _ => false
}

This first solution uses pattern matching to investigate the list recursively. It checks if the list is empty or if it contains only one element and returns true. Otherwise, it checks if the head of the list equals the last element. If so, the rest of the list (its middle part) is passed recursively to the function. This is one more case where we can see the great power of scala’s pattern matching in action.

Also, the solution will work with strings as well, so it matches the dictionary definition – just call toList on the string. Sample execution from the REPL:

scala> isPalindrome("oio".toList)
res11: Boolean = true

scala> isPalindrome("oioo".toList)
res12: Boolean = false

To be honest, I don’t feel too much creative when thinking about this problem, so the next solution is quite similar to the previous one, but without pattern matching:

def isPalindrome(list: List[Any]): Boolean = {
  if (list.isEmpty || list.size == 1) true
  else if (list.head == list.last) isPalindrome(list.slice(1, list.size-1))
  else false
}

Now lets take a look at the original solution and… I’m stunned by its simplicity. While I went all fancy at things like pattern matching, the original solution goes like this:

def isPalindrome[A](ls: List[A]): Boolean = ls == ls.reverse

Yeah, I should have thought of that…

Posted in scala | Tagged , , , , , , , | Leave a comment

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…

Posted in scala | Tagged , , , , , , , | 4 Comments

The Developers Conference 2011

From July 6 to 10 happened The Developers Conference 2011 down here in São Paulo. The other editions were really good and, better, this one topped all of them. It was a really fun and productive event. I had the chance to meet friends and to get to know new people. If you were not there, #protip for you: BE THERE NEXT YEAR. Really.

Before talking more about the conference, I have to thank Globalcode (in special Vinicius and Yara). They did a great job =)

Since last year, the premise of the conference is to have people from all kinds of backgrounds, from a lot of different communities, like Java, Ruby, Python, Agile, Javascript, .NET and lots more. Each day featured five different tracks, with different topics, to fit all those communities and tools. The result is that we had a lot of different people and lots of opportunities to talk to people you usually would not encounter. This was a really enriching experience.

In a personal level, this conference was special to me: I made two ‘speaking’ participations. In one of them I talked about Scala, an introductory talk (you can find the sample code used in the talk in my github). The other one was a panel consisting of people from different languages on the jvm – lots of fun =)

In the event, I had one personal fail moment, that should remain as a tip for everyone out there. In a given moment, when talking to someone, I was asked for my business card… and didn’t have any on me. So the obvious tip: always have business cards with you. Always.

Now, if you follow my posts about events you may have noticed that this one is a little different. It contains no pictures. This is due to a second fail, that happened on this last Monday. I lost (or it got stolen…) my mobile. And with it, all the pictures from the entire event. Sorry =(

Posted in java | Tagged , , , , , , , , | 3 Comments

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 =)

Posted in scala | Tagged , , , , , , | Leave a comment

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?

Posted in java, scala | Tagged , , , , , , , | 1 Comment

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

Posted in java, scala | Tagged , , , , , , | Leave a comment

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 =)

Posted in scala | Tagged , , , , , , | Leave a comment

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!

Posted in java, scala | Tagged , , , , , , , | Leave a comment

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.

Posted in scala | Tagged , , | Leave a comment

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!

Posted in scala | Tagged , , , , , , , | 2 Comments