Sunday, January 27, 2013

The 16th President of the United States. Abraham Lincoln once said: "As our case is new we must think and act anew". In software engineering things probably aren't as dramatic as civil wars and abolishing slavery but we have interesting logical concepts concerning "case". In Java the case statement provides for some limited conditional branching. In Scala, it is possible to construct some very sophisticated pattern matching logic using the case / match construct which doesn't just bring new possibilities but a new type of thinking to realise new possibilities.

Let's start with a classical 1st year Computer Science homework assignment: a fibonacci series that doesn't start with 0, 1 but that starts with 1, 1. So the series will look like: 1, 1, 2, 3, 5, 8, 13, ... every number is the sum of the previous two.

All straight forward. If 0 is passed in it counts as the first element in the series so 1 should be returned. Note: to add some more spice to the party and make things a little bit more interesting I added a little bit of logic to return 0 if a negative number is passed in to our fibonacci method.

It is possible to test for multiple values on the one line using the | notation. I do this to return a 1 for both 0 and 1 on line 4 of the example.

There is no need for multiple return statements. In Java you must use multiple return statements or multiple break statements.

Pattern matching is an expression which always returns something.

In this example, I employ a guard to check for a negative number and if it a number is negative zero is returned.

In Scala it is also possible to check across different types. It is also possible to use the wildcard _ notation. We didn't use either in the fibonacci, but just to illustrate these features...

def multitypes(in: Any): String = in match {
case i:Int => "You are an int!"
case "Alex" => "You must be Alex"
case s:String => "I don't know who you are but I know you are a String"
case _ => "I haven't a clue who you are"
}

Pattern matching can be used with Scala Maps to useful effect. Suppose we have a Map to capture who we think should be playing in each position of the Lions backline for the Lions series in Austrailia. The keys of the map will be the position in the back line and the corresponding value will be the player who we think should be playing there. To represent a Rugby player we use a case class. Now now you Java Heads, think of the case class as an immutable POJO written in extremely concise way - they can be mutable too but for now think immutable.

In this example we have players for every position except inside centre - which we can't make up our mind about. Scala Maps are allowed to store nulls as values. Now in our case we don't actually store a null for inside center. So, instead of null being returned for inside centre (as what would happen if we were using a Java HashMap), the type None is returned.

For the other positions in the back line, we have matching values and the type Some is returned which wraps around the corresponding RugbyPlayer. (Note: both Some and None extend from Option).

We can write a function which pattern matches on the returned value from the HashMap and returns us something a little more user friendly.

This example doesn't just illustrate pattern matching but another concept known as extraction. The rugby player when matched is extracted and assigned to the rugbyPlayerExt. We can then return the value of the rugby player's name by getting it from rugbyPlayerExt. In fact, we can also add a guard and change around some logic. Suppose we had a biased journalist (Stephen Jones) who didn't want any Irish players in the team. He could implement his own biased function to check for Irish players

Single Parameter functions

Consider a list of numbers from 1 to 10. The filter method takes a single parameter function that returns true or false. The single parameter function can be applied for every element in the list and will return true or false for every element. The elements that return true will be filtered in; the elements that return false will be filtered out of the resultant list.

Now now now, listen up and remember this. A pattern can be passed to any method that takes a single parameter function. Instead of passing a single parameter function which always returned true or false we could have used a pattern which always returns true or false.

What this example is saying is patternToUseLater is a partial function that takes a string and returns a string. The last statemeent in a function is returned by default and because the case expression is a partial function it will returned as a partial function and assigned to pattenrToUseLater which of course can use it later.

Finally, Johnny Sexton is a phenomenal Rugby player and it is a shame to hear he is leaving Leinster. Obviously, with Sexton's busy schedule we can't be sure if Johnny is reading this blog but if he is, Johnny sorry to see you go we wish you all the best and hopefully will see you back one day in the Blue Jersey.

It was considered best practice to always check if your logging was enabled for the appropriate level before performing any String concatenation. I even remember working on a project ten years ago (a 3G radio network configuration tool for Ericsson) where String concatenation for logging actually resulted in noticeable performance degradation.

Since then, JVMs have been optimised and Moore's Law has continued so that String concatenation isn't as much of a worry as it used to be. Many frameworks (for example Hibernate), if you check the source code you'll see logging code where there is no check to see if logging is enabled and the string concatenation happens regardless. However, let's pretend concatenation is a performance issue. What we'd really like to do is remove the need for the if statements in order to stop code bloat.

The nub of the issue here is that in Java, when you call a method with parameters the values of the parameters are all calculated before the method is called. This why the if statement is needed.

simpleComputation(expensiveComputation());// In Java, the expensive computation is called first.
logger.log(Level.INFO, "Log this " + message);// In Java, the String concatenation happens first

Scala provides a mechanism where you can defer parameter evaluation. This is called call-by-name.

The => before the String types means that the String parameter is not evaluated before invocation of the log function. Instead, there is a check to confirm the logger level value is at the appropriate value and if so the String will then evaluated. This check happens within the log function so there is no need to put the check before every invocation of it. What about that for code re-use?

Anything else?

Yes when pass-by-name is used, the parameter that is passed-by-name isn't just evaluated once but everytime it is referenced in the function it is passed to.
Let's look at another example

In this example, we can see that nanoTime() isn't just executed once but everytime it is referenced in the function, printTime it is passed to. This means it is executed three times in this function and hence we get three different times. 'Til the next time, take care of yourselves.

Wednesday, January 16, 2013

Problem?

We want a function that will take an List of Rugby players as input and return those players names that play for Leinster and can run the 100 meters from the fastest to the slowest.

Step 1: Have a representation for a Rugby player.

Ok so it's obvious we want something like a POJO to represent a Rugby player. This representation should have a player's name, their team and the time they can the 100 meters in. Let's use Scala case class construct which removes the need for boiler plate code.

The code above should be self explanatory. The various rugby players are instantiated. Note the inferred typing. There is no need to declare any of the rugby players as RugbyPlayers types. Instead, it is inferred. Another thing that is interesting is the keyword val is used. This means the reference is immutable It is the equivalent to final in Java.

Step 3: Write the function

The function begins with def keyword signifying a function declartion.

A List of RugbyPlayerCaseClass instances are taken in as input. The List type is a Scala type.

The return type is optional. In this case it is not explictly specified as it is inferred.

The part to the left of the = is what the function does. In this case the function invokes three difference collection operators.

.filter(_.team =="Leinster) - this iterates over every element in the List. In each iteration the _ is filled in with the current value in the List. If the team property of the current Rugby player is Leinster the element is included in the resulting collection.

.sortWith(_.sprintTime100M < _.sprintTime100M) - sortWith is a special method which we can use to sort collections. In this case, we our sorting the output fromthe previous collection operator and we are sorting based on the sprintTime for 100M.

.map(_.name) - this maps every element from the output of the sort operator to just ther name property.

The function body does not need to be surrounded by {} because it is only one line code.

There is no return statement needed. In Scala, whatever the last line evaluates to will be returned. In this example since there only is one line, the last line is the first line.

Sunday, January 13, 2013

Nearly everyone who learns Scala can get confused over the word partial used in the contexts:

Partial functions

Partially applied functions

Let's look at both.

Partially applied functions

Scala gets its functional ideas from classical languages such as Haskell (Haskell 1.0 appeared in same year as Depeche Mode's Enjoy the Silence and Dee Lite's Groove is in the Heart in 1990). In functional languages a function that takes two parameters that returns one parameter can be expressed as a function which takes one of the input parameters and returns a function that takes the other input parameter and returns the same output parameter.

f(x1, x2) = y

f(x1) = f(x2) = y

A cheesey analogy would be to time travel back to 1990 and find yourself a juxebox. Put money in for two selections and select Depeche Mode first and Dee Lite second, walk away and throw a few shapes as they are played one after the other. Or, put in your money for two selections select Depeche Mode and then don't make another selection. Don't walk away just yet. The well engineered Juxebox should prompt you for another selection (give you another function) and then you can select Dee Lite (pass in the second parameter). So, the end output in both cases is the same music in the same order.

In Scala, when only some parameters are passed to a function to make another function it is said to be a partial application of that function.

So consider the function:

def minus(a: Int, b: Int) = "answer=" + (a-b)

Now, let's partially apply this function by passing in some parameters and making another function.

val minus50 = (a: Int) => minus(a, 50);

In this case minus50 is a partial application of minus.

We can do:

minus50(57); // outputs 7.

Note: we can also partially apply using the _ notation and a save ourselves a little bit of finger typing.

val minus50 = minus(_:Int, 50);

Partial functions

A partial function is a function that is valid for only a subset of values of those types you might pass into it. For example,
Consider the mathematical function where x is set of all number from 1 to 100:

f(x) = x + 5;

A function is said to be partial if the function is only applied to a subset in set of element of x.
So if we only want to define the function

f(x) = x + 5

for the numbers 1,2,3,4,5,6,7 but not 8,9,10, ... - we define a partial function.

f(x')=x+5

where x' = {1,2,3,4,5,6,7}

In Scala, a PartialFunction inherits from Function and adds two interesting methods:

isDefinedAt - this allows us to check if a value is defined for the partial function.

orElse - this allows partial functions to be chained. So if a value is not defined for a function it can be passed to another function. This is similar to the GoF Chain of Responsibility pattern.

Ok so open up a Scala REPL and create the following partial function which will add 5 to an integer as long as the integer is less than 7.

When you try this for a value less than or equal to 7, you will see the result no problem

scala > add5Partial(6);
res1: 11

When you try it for a value greater than 7 you don't get a nice clean answer.

scala> myPartial(42);
scala.MatchError: 42 (of class java.lang.Integer)
at $anonfun$1.apply$mcII$sp(:7)
at .(:9)
at .()
at .(:11)
at .()
at $print()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
at java.lang.Thread.run(Thread.java:722)

The use of isDefinedAt() should now be becoming apparent. In this case, we could do:

And yes for this specific case, this will work. But what if your functions/ commands become more complex. Are you go to hang around in if / else land? Probably not. 'Til the next time, take care of yourselves.

Sunday, January 6, 2013

Functions are an important part of the Scala language. Scala Functions can have a parameter list and can also have a return type. So the first confusing thing is what's the difference between a function and a method? Well the difference is a method is just a type of function that belongs to a class, a trait or a singleton object.
So what's cool about functions in scala? Well you can define functions inside functions (which are called local functions) and you can also have anonymous functions which can be passed to and returned from other functions. This post is about those anonymous functions which are referred to as function literals.
As stated, one of the cool things about function literals is that you can pass them to other functions. For example, consider snippet below where we pass a function to a filter function for a List.

List(1,2,3,4,5).filter((x: Int)=> x > 3)

In this case, the function literal is (x: Int)=> x > 3
This will output: resX: List[Int] = List(4, 5).
=> called "right arrow" means convert the thing on the left to the thing on the right. The function literal in this example is just one simple statement (that's what they usually are), but it is possible for function literals to have multiple statements in a traditional function body surrounded by {}. For example, we could say:

List(1,2,3,4,5).filter((x: Int)=>{
println("x="+ x);
x > 3;})

which gives:

x=1
x=2
x=3
x=4
x=5
resX: List[Int] = List(4, 5)

Now one of the key features of Scala is to be able to get more done with less code. So with that mindset, let's see how we can shorten our original function literal. Firstly, we can remove the parameter type.

List(1,2,3,4,5).filter((x)=> x > 3)

This technique is called target typing. The target use of the expression in this case, what is going to filter is allowed to determine the type of the x parameter.
We can further reduce the strain on our fingers by removing the parentheses. This is because the parentheses were only there to show what was been referred to as Int in the parameter typing. But now the typing is inferred the brackets are superflous and can be removed.

List(1,2,3,4,5).filter(x => x > 3)

Shorten it even more? yeah sure...
We can use the placeholder underscore syntax.

List(1,2,3,4,5).filter(_ > 3)

Underscores have different meanings in Scala depending on the context they are used. In this case, if you are old enough think back to the cheesey game show blankety blank.

This gameshow consisted of of sentences with blanks in them and the contestants had to make suggestions for what went into the blank. In this example, the filter function fills in the blanks with the values in the Lists it is being invoked on. So the filter function is the blankety blank contestant and the List (1,2,3,4,5) are what the filter function uses to fill the blank in.
So now our code is really neat and short. In Java to achieve the same, it would be:

Tuesday, January 1, 2013

Right time to broaden the horizons. It's 2013 and I am going to start blogging about Scala which I am trying learn. I am going to start with for loops.

for(i
It is quite easy to figure out what is going on here, without even mentioning the word Scala. Hey it's just a for loop and yeah it iterates from 1 to 5 and there's probably some type inference going on - since Scala is statically typed. That's all fine, but, I find it useful when trying to learn a new language, to learn the language of that language. For anyone coming from a Java background the 'generator. Why? Because it generates individual vales from a range which in this case is the 1 to 5 part.

There is not much else interesting in this example except the intent of 2 spaces - Java programmers will be use to 4. So what else? Well there are two styles of for loops in Scala:foreach and for. The former is intended for a functional approach and I'll cover this is another post. The later is suited for imperative style. In fact the for and foreach constructs are an excellent example of how Scala facilitates both imperative and functional progamming.

Give me more?

Sure, let's have at look at more tricks with for loops using the imperative approach.

There is no need to explictly make the class ForLoopExample public. This is because public is default access level in Scala. Where you said public in Java you say nothing in Scala.

The only difference between forExampleWithTo and forExampleWithUntil is that one uses to in its range and the other uses until. In these examples to means 1,2,3,4,5 and until means 1,2,3,4 - i.e. the last element is not included.

forExampleWithMultipleRanges shows how to iterate over multiple ranges. In addition, note the statement in the for loop are enclosed in {}. The {} are required when multiple statements are in each iteration. If there is only one statement they can be omitted.

forExampleWithFilter shows how to filter out values from the list.

forExampleStoreValues shows how to store the result of the iteration values from a for list.

Rather than MainRunner being declared as a class, it is declared as an Object. This means it is singleton.

The main() method is similar to Java's public static void main. Except there is no need for public (it's the default). There is no need for static (we are in a singleton) and there is no need to declare the return type. You see Scala you get more code with less typing.

In some cases I omit the () from the method invocation. In cases when a method has no arguments Scala allows the omissions of the (). However, this notation should only be used when the method has no side effects i.e. the method does not change the state of anything - so I am only using it here to for purposed of illustration.

About Me

Alex Staveley is a software professional passionate about software
engineering and technical architecture. He blogs about architectural
approaches, Java topics, web solutions and various technical bits and
pieces.