Saturday, November 21, 2009

Programming in Scala – Part 2/?

In my previous post, we got started with simple Scala HelloWorld and moved on to write a bubble sort in Scala. This time let us look at some differences between a “var” and a “val” in scala. I hope you all know what “immutable” means – simply put Strings in Java/.NET are immutable. Anytime you modify a string, a new object of string is created – they cannot be changed in place. Well, in scala when you declare a variable with a “val” it would be immutable. Look at the following scala code.

object ValVar
{
def main(args: Array[String])
{
val immutableValue = 200
//immutableValue = 20 -> gives compiler error
var mutableValue = 200
mutableValue = 20
println("Immutable : "+immutableValue+"\n Mutable : "+mutableValue)
}
}


The decompiled program would look like shown in Java



import java.rmi.RemoteException;
import scala.Predef.;
import scala.ScalaObject;
import scala.ScalaObject.class;
import scala.StringBuilder;
import scala.runtime.BoxesRunTime;

public final class ValVar$
implements ScalaObject
{
public static final MODULE$;

static
{
new ();
}

public ValVar$()
{
MODULE$ = this;
}

public void main(String[] args) {
int immutableValue = 200;

int mutableValue = 200;
mutableValue = 20;
Predef..MODULE$.println(new StringBuilder().append("Immutable : ").
append(BoxesRunTime.boxToInteger(immutableValue)).
append("\n Mutable : ").
append(BoxesRunTime.boxToInteger(mutableValue)).toString());
}

public int $tag()
throws RemoteException
{
return ScalaObject.class.$tag(this);
}
}


Clearly, it does not look like "immutable" variables are declared final in the Java code. So it appears to me that Scala compiler does the job of making sure that the val'bles are immutable. For those curios to see what happens if you attempt to change a val'ble, see the screenshot below. Also it would be interesting to note that the scala compiler takes care of optimizing our string concatenation to make use of String builder, just like the javac!



image



So what did we learn?: If you wish to keep changing the values for a variable, then use "var" and if you want immutable variables, use "var".



Now that we know how to create both variables and val’bles, let us look at some fancy stuff that we could do with lists.



Whats your range?



Let us say, we need all odd numbers between 20 and 2000 which are divisible by both 5 and 7. If you were like me, we write the program to look like shown below.



object RangeAction1
{
def main(args: Array[String])
{
for(i <- 20 to 2000)
{
if( i % 5 == 0 && i % 7 == 0)
println(i)
}
}
}


Can we do any better? This looks too long now that I have been imagining things, increasing expectations about scala being so nice.



object RangeAction1
{
def main(args: Array[String])
{
(20 to 2000).filter(i=>i%5==0&&i%7==0).foreach(i=>println(i))
}
}


When we say “20 to 2000”, it returns a Range object. Look in the documentation to see what all magic could we do with range. Similarly if we were to work with lists, we could do something similar. Now to add 1 cent to the 3 cents we covered so far, what if i want the range to start with 20 and end with 2000 but increment by 10 and exclusive of 2000.




(20 until 2000 by 10).filter{i=> i % 5 == 0 & i % 7 == 0}.foreach{i=> println(i)}


Also, I wanted to be more like a regular programmer and put my closure inside {} instead of (). More fun later!

Friday, November 20, 2009

Scala for dummies like me!

Well! what should I be saying? I am that kind of person who keeps shifting from one interest to another. Once I am extremely interested in .NET (and I still am, but .NET is now an ocean – would take me too long to catch up with everything) and now I want to explore Scala – all new programming language on the JVM (new to me!) which has been receiving rave reviews. So, I went ahead and ordered Programming in Scala book on a1books.com (which by the way is a great site) but unfortunately I did not receive my copy yet. So here i am with all intention to do something with Scala but am out of resources (no offense but there are no simple tutorial on Scala which is interesting and which doesn’t make me fall asleep in 2 minutes).

Lets first get started and write a Hello World program.

class HelloWorld
{
def main(args: Array[String]){
println("Krishna Vangapandu - Hello Scala world!");
}
}




When you compile this and execute it, you would get a “java.lang.NoSuchMethodException: HelloWorld.main is not static”. Well, the mistake that I did was to put a “class” – but it should be object. So the hello world would be



object HelloWorld
{
def main(args: Array[String]){
println("Krishna Vangapandu - Hello Scala world!");
}
}


So what's the difference between "class" and an "object". Obviously there is no problem for the compiler, only the runtime blows! So what does the documentation say about this? Well even better lets use a decompiler to decompile the .class file we obtained and see how the scala code would when written in java. By the way, I am using this decompiler - which i should say is freaking awesome.


"class HelloWorld" decompiled.




import java.rmi.RemoteException;
import scala.Predef.;
import scala.ScalaObject;
import scala.ScalaObject.class;

public class HelloWorld
implements ScalaObject
{
public void main(String[] args)
{
Predef..MODULE$.println("Krishna Vangapandu - Hello Scala world!");
}

public int $tag()
throws RemoteException
{
return ScalaObject.class.$tag(this);
}
}


"object HelloWorld" decompiled.



import java.rmi.RemoteException;

public final class HelloWorld
{
public static final void main(String[] paramArrayOfString)
{
HelloWorld..MODULE$.main(paramArrayOfString);
}

public static final int $tag()
throws RemoteException
{
return HelloWorld..MODULE$.$tag();
}
}


But what the hell is a $tag() method? Well, I looked into the source code which had a comment on the $tag method which says



This method is needed for optimizing pattern matching expressions which match on constructors of case classes.  




Well, then what is the HelloWorld actually doing? Well, looks to me it was using the HelloWorld$ which was also generated by “scalac”. I cannot dig into what is  going on here, may be sometime in the future.



So far, what I understood is that “object” creates a final class whereas “class” creates a ScalaObject and methods inside would all be instance methods. So anything declared “object” can act only as a static-only container.



Lets do a simple bubble sort program in Scala. What should we be knowing to write a button sort?




  1. Assuming we pass the numbers to sort from command line, how do we convert strings to numbers ?


  2. How do we loop the array?



object BubbleSort
{
def main(ip_args: Array[String]) //we shall get the input numbers to sort into "args"
{
/*
we have a collection of strings, we should get a collection of numbers.
so we use the map which says for each i in the ip_args,
return the value after converting into expression. we get a 1 to 1 returned array.
*/
val args = ip_args.map { i => Integer.parseInt(i)}

/*
Looping : for index j which starts from 0 and ends at args.length-1 (inclusive)
*/
for(j <- 0 to args.length-1)
{
for(i <- 0 to args.length-2-j)
{
if(args(i) > args (i+1))
{
//we do an ascending order sort.
// Swap routine is shown belo.
val temp = args(i) //this is how we define variables in scala
args(i) = args(i+1)
args(i+1) = temp
}
}
}
//print all the numbers
for(i <- 0 to args.length-1)
println(args(i))
}
}


I do agree that even without the comments the code does not look as concise as it should be. But right now, we are just getting started – we would slowly look at how we can write concise code when we think functional programming (I am saying this with my past experience with Groovy and C# Closures – by functional, 90% of the time I mean closures – which I know is not accurate).I have also observed that when you compile the BubbleSort.scala, you end up getting more than one .class files - which I believe is for the anonymous method (closure) we used.



That's it! for this post. See you soon with functional programming using Scala!

Thursday, November 12, 2009

Working with JQuery and list boxes

Code (read comments):

<html> 
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
/*
when the document is ready (after all the HTML page is loaded, this shall be executed)
we attach the event handlers.
*/
$(document).ready(function(){ attachEventHandlers(); });
function attachEventHandlers(){
/*
In this method we attach the function(){} to the change event on all the <select> items.
The code inside the function(){} shall be executed when item selections are changed on the select box.
*/
$("select").change(function(){
//using "this" to access the current listbox. the jQuery wrapper would be $(this)
var selectedItems = $(":selected",this);
$("#itemsCount").text(selectedItems.length); //set the items selected count.
var toAppendHtml = ""; //lets store the html that we shall put inside the itemsSelected element.
//for each selected item we add a new line with selected item's text and value to the toAppendHtml.
selectedItems.each(function(){
toAppendHtml += $(this).text() +" : "+$(this).val()+"<br/>";
});
//finally put everything in there as html content to itemsSelected.
$("#itemsSelected").html(toAppendHtml);
});
/*
Alternatively you can use ExternalFunction. The external function should have one parameter "e" called the event object.
$("select").click(ExternalFunction);
*/
}
/*
function ExternalFunction(e)
{
//now within this function, the element which raised the event can be accessed using "this", or "e.currentTarget".
//So the statement "this == e.currentTarget" will always be true.
alert($(":selected",this).length);
}
*/
</script>
<style type="text/css">
select{
width: 100px;
height: 200px;
}
</style>
</head>
<body>
<select name="items" id="items" multiple="true">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
<option value="6">Item 6</option>
<option value="7">Item 7</option>
</select>
<p/>
<div>total items selected : <span id="itemsCount">0</span></div>
<span>Selected Items are </span>
<div id="itemsSelected"/>
</body>
</html>

Thursday, November 05, 2009

Problem running Scala

I was just trying to run scala on my machine and failed to do so with an error message “…..\java.exe unexpected at this time.” Look at the screenshot shown below.

image

Well, the problem was that environment variables for JAVA was set up using JAVA_HOME variable. The JAVA_HOME environment variable was pointing to the JDK directory and the Path was modified to include the “%JAVA_HOME%\bin” directory.

I removed the JAVA_HOME and then modified the path to specify the complete path to the JDK bin folder and it works now. :)

I might be talking more about Scala in the future, the concurrency scala supports appears to be interesting.