Wednesday, April 3, 2013

Interesting case for var -> val conversion in Scala

While Scala supports imperative as well as functional style of programming, it recommends programming in the latter. One of the challenges I faced was getting rid of a counter in the following BFS (Breadth First) style recursion (mutable to immutable variable conversion). I wont go into specifics but rather look at the pattern to be used here:

def BFSCounter(money: Int, coins: List[Int]): Int = {
    var n = 0
    // termination checks
    for (// loop dependent on input parameters
        n += BFSCounter( ...)
    n
}

The above code launches multiple recursions in each call of BFSCounter and the variable n which maintains the count must be incremented and returned. 

The strategy to get rid of the mutable variable is to pass the counter from one call of BFSCounter to another.  To do that we must also make the calls to BFSCounter a constant (independent of variables or input parameters). This means understanding the traversal pattern, termination checks etc. The final code looks like the following:

def BFSCounter2(money: Int, coins: List[Int]): Int = {
    // termination checks
    val count1 = BFSCounter2(...0..)
    BFSCounter2(count1)
}

Note that you may be able to reduce the code to just one call to BFSCounter2 or maybe you will need three calls. The point is that the number of calls should be finite and the counter is passed into the BFSCounter2 and passed back out as return value. The last call's return value is the final return value of the function.

No comments: