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

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.

Post a Comment

Your email is never published nor shared. Required fields are marked *