Tag: scala


Why Scala? (2) Compact syntax applied to probabilistic actions

July 27th, 2010 — 7:13am

As a little fun project, I developed some probabilistic cellular automata with Scala and very basic AWT graphics. I continue to become more proficient with Scala, and it feels increasingly natural to use. During this exercise I came up with something that I thought was particularly elegant, and that I am pretty sure would have been a lot less readable in Java. I will just reproduce the interesting bits. The basic idea is that I want cells on a 2D grid to take certain redrawing actions according to given probabilities. First, I define this utility function:

object Util {
 
	//sum of floats (probabilities) should be at most 1.0
	def multiAction(acts: Seq[Tuple2[()=> Unit, Float]]) = {
		val r = Math.random
		var soFar: Float = 0
		var acted = false
		for ((act,prob) <- acts) {
			soFar += prob
 
			if (soFar > r && !acted) {
				act()	
				acted = true
			}
		}
	}
 
}

The idea here is that we supply a list of tuples. The first element of each tuple is a function, and the second element is a float value between 0 and 1 representing the probability that each function is evaluated. Only one of the functions supplied is actually evaluated.

This is how I put it to use (excerpt from another class):

Util.multiAction(
  List( 
  (() => {
     cellsWrite(x, y-1) = cellsRead(x, y-1) + 0.01f;
     cellsWrite(x, y+1) = cellsRead(x, y+1) + 0.01f 
    }, 0.2f),
  (() => { 
     cellsWrite(x+1, y) = cellsRead(x+1, y) + 0.01f;
     cellsWrite(x-1, y) = cellsRead(x-1, y) + 0.01f 
    }, 0.1f)
 )
)

Once you take in the braces here it is actually quite simple. We have two anonymous functions taking zero parameters of two statements each. The first one has probability 0.2 and the second probability 0.1, meaning that there’s a 70% probability that nothing will happen. We can also make an arbitrarily long list of such functions on the fly.

To the best of my knowledge, the only way of reproducing this flexibility in Java would be to create anonymous inner classes and put them inside an array. Certainly that would be quite a bit more verbose than this.

Comment » | Software development

Meta notes: 1+ year with Monomorphic blogging

May 29th, 2010 — 12:28am

After 13 months and 51 posts, my experiments in blogging continue, although they are perhaps better described as polymorphic than monomorphic. Maybe it’s time for some reflections.

On the whole blogging in this format and at this frequency has been a pretty fun and fulfilling process. I get to practice writing free-form, nonscientific texts, and even if many of them might not be read by so many people, the idea that they might be turns it into a useful exercise.

Recently Flattr buttons were added to this blog, which allows users who use the service to donate money and show appreciation for my texts (some such people indeed exist – thanks a lot, all two of you!). Initially I had a single button for the entire blog, but now I am trying out a format where I have one button per post.

I’ve noticed, on this blog and elsewhere, that I can’t quite decide if I should write with British or American English. I feel culturally uncertain as a writer of this language. But recently I’ve come to think that I should embrace my European background, so more of the British variety in the future is a likely prospect.

Topics have been varied. The tag and category systems have been used in an attempt to bring some order to the table, but they’ve become too chaotic to be useful. A restructuring is perhaps in order during the next 13 months.

One of the most popular topics I’ve written about has been the Scala language. People tend to google Scala a lot, and it’s actually really uplifting to see the interest in it (since I hold it to be a way forward). If you are a blogger who wants to get a billion page views, write about Scala. I don’t want to consciously pander to the readers too much, so in itself it is not a reason for me to write about the topic. I will write about Scala when I want to say something about it. (A difficult principle to really practice.)

I’ve tried out some different WordPress themes occasionally, but so far I haven’t found anything I like better than this “Infinimum” theme. It feels very clean, functional and modern.

That will be enough of the reflections for now.

2 comments » | Uncategorized

Why Scala? The mixing of imperative and functional style

February 11th, 2010 — 1:15pm

Scala is a little wonderland sprinkled with useful things you can mix and match as you like to improve your coding experience while staying on the Java platform. The Option classes, the structural case matching, the compact declarations, lazy evaluation… the list goes on. But at the heart of it is the decision to mix freely the functional and imperative programming styles.

How does this work in practice?

  • Statements can have side effects, like in Java
  • The final statement evaluated in a function is its return value by default
  • Every statement evaluates to a value, even control flow statements like if… else, unlike in Java

The bottom line is that some problems call for a functional programming style, and others for an imperative one. Scala doesn’t force you into a mold, it just gives you what you need to express what you’d like to express. This can lead to very compact code. Here’s a function that recursively finds all files ending in .java starting in a given directory. The File class here is the standard Java java.io.File!

Remember, the last expression evaluated is the return value.

 def findJavaFiles(dir: File): List[File] = {
    val files = dir.listFiles()
    val javaFiles = files.filter({_.getName.endsWith(".java")})
    val dirs = files.filter({_.isDirectory})
    javaFiles.toList ++ dirs.flatMap{findJavaFiles(_)}
  }

But we can write it even more compactly at the expense of some clarity:

 def findJavaFiles(dir: File) = {
    val files = dir.listFiles()
    files.filter(_.getName.endsWith(".java")).toList ++
 files.filter(_.isDirectory).flatMap{findJavaFiles(_)}
  }

Now write this function in Java and see how many lines you end up with.

Comment » | Software development

An immutable MultiMap for Scala

December 9th, 2009 — 3:41pm

The Scala collections library (in version 2.7.7) has a MultiMap trait for mutable collections, but none for immutable ones. I hacked something up to use while waiting for an official version. I’m finding this to work well, but I don’t have much experience with collections design, so it’s likely to have some flaws. Also, this is a class and not a trait, so you can’t use it with any map you like. And from a concurrency perspective, maybe it’s sometimes better to use backing collections other than the HashSet and the HashMap.

 
import scala.collection.immutable._
 
/**
A multimap for immutable member sets (the Scala libraries 
only have one for mutable sets). 
*/
class MultiMap[A, B](val myMap: Map[A, Set[B]]) {
 
	def this() = this(new HashMap[A, Set[B]])
 
	def +(kv: Tuple2[A, B]): MultiMap[A, B] = {
	  val set = if (myMap.contains(kv._1)) {
		  myMap(kv._1) + kv._2
	  } else {
		  new HashSet() + kv._2	     	   
	  }
 
	  new MultiMap[A, B](myMap + ((kv._1, set)))
	}
 
	def -(kv: Tuple2[A, B]): MultiMap[A, B] = {
	  if (!myMap.contains(kv._1)) {
	    throw new Exception("No such key")
	  }
	  val set = myMap(kv._1) - kv._2
	  if (set.isEmpty) {
	    new MultiMap[A, B](myMap - kv._1)
	  } else {
		  new MultiMap[A, B](myMap + ((kv._1, set)))
	  }
	}
 
	def entryExists(kv: Tuple2[A, B]): Boolean = {
	  if (!myMap.contains(kv._1)) {
	    false
	  } else {
	    myMap(kv._1).contains(kv._2)
	  }
	}
 
    def keys = myMap.keys
 
     def values: Iterator[Set[B]] = myMap.values
 
    def getOrElse(key: A, elval: Collection[B]): Collection[B] = {      
      myMap.getOrElse(key, elval)
    }
 
    def apply(key: A) = myMap(key)
 
 
 
}

Usage:

 
   var theMultiMap = new MultiMap[String, Int]()
 
   theMultiMap += (("george", 1))
   theMultiMap += (("george", 3))
   theMultiMap += (("bob", 2))
   theMultiMap -= (("george", 1))

Comment » | Software development

Where is Java going?

November 22nd, 2009 — 2:51pm

creative

Today, Java is one of the most popular programming languages. Introduced in 1995, it rests on a tripod of the language itself, its libraries, and the JVM. In the TIOBE programming language league charts, it has been at the top for as long as the measurements have been made (since 2002), overtaken by C only for a brief period due to measurement irregularities.

Yet not all is Sun-shine in Java world. Sun Microsystems is about to be taken over by Oracle, pending EU approval. (EU is really dragging its feet in this matter but it seems unlikely they would really reject the merger). Larry Ellison has voiced strong support for Java and for Sun’s way of developing software, so maybe this is really not a threat by itself. But how far can the language itself go?

The Java language was carefully designed to be relatively easy to understand and work with. James Gosling, its creator, has called it a blue collar language, meaning it was designed for industrial, real world use. In a world where C++ was the de facto standard for OO programming, Java was a big step forward in terms of ease of development, with its lack of pointers and strong type system – to say nothing of its garbage collection. Many classes of common programming errors were removed altogether. However, in the interests of simplicity and clarity, some tradeoffs were made. The language’s detractors today point to problems such as excessive verbosity, the lack of closures, the limited generics, and the checked exceptions.

For some time there has been a lot of exciting alternative languages available on the JVM. Clojure is a Lisp dialect. Scala, the only non-Java JVM language I have used extensively, mixes the functional and object oriented paradigms. Languages like JPython and JRuby basically exist to allow scripting and interoperability with popular scripting languages on the JVM.

Today it seems as if the JVM and the standardized libraries will be Java’s most prominent legacy. The language itself will not go away for a long time either – considering that many companies still maintain or develop in languages like Cobol and Fortran, we will probably be maintaining Java code 30 years from now (what a sad thought!), but newer and more modern JVM languages will probably take turns being number one. The JVM and the libraries guarantee that we will be able to mix them relatively easily anyway, unless they stray too far from the standard with their custom features.

So in hindsight, developing this intermediate layer, this virtual machine – and disseminating it so widely –  was a stroke of genius. Will it be that in future programming models we have even more standardized middle layers, and not just one?

Meanwhile, there’s a lot of debate about the process being used to shape and define Java. For a long time, Sun employed something called the Java Community Process, JCP, which was supposed to ensure openness. Some people proclaim that the openness has ended. To take one example, very recently, Sun announced that there will be support for closures in Java 7, after first announcing that there would be no support for closures in Java 7. The process by which this decision has been managed has been described as not being a community effort. Some aspects of Java are definitely up in the air these days.

Comment » | Software development

Back to top