Debugging functional code in Scala

I know being concise is very nice, and I agree with you that IDEs should help with the debugging in these situations. But for the time being I have changed my coding style to assist with debugging. In my personal style I would have implemented your example as:

val noZeroLs = ls.filter(_>1)
val sortedLs = noZeroLs.sort(_<_)
val indexedNoZeroLs = sortedLs.zipWithIndex
val everySecondIndexedL = indexedNoZeroLs.filter(v => (v._2) % 2 == 0)
val everySecondL = everySecondIndexedL.map(_._1)

Coming up with meaningful names is difficult/laborious, but it does help you identify silly bugs; may help others to understand what is going on; and definitely helps with debugging.


I think everybody's advice to break this thing down to more manageable chunks is the best approach. One trick for debugging smaller expressions is to steal Ruby's tap function, as described here. "tap" allows you to stick an expression in the middle of a chain like this, and perhaps print out some debug values, like so:

val ls = List(1,2,3).map(_ * 2)
                .tap(soFar => println("So far: " + soFar))
                .map(_ * 2)
println(ls)

This will print out:

So far: List(2, 4, 6)
List(4, 8, 12)

It helps me every once in a while.


In a purely functional setting, stepping through is not nearly as useful as you might think. Since everything is composed of pure functions, you can just test those pieces individually using a process of elimination. In a lazy evaluation setting, stepping through code is even less useful.

Debugging programs in Haskell, for example, you would not at all be interested in tracing function calls. What you are interested in is a trace of intermediate function return values. It would be a very useful feature in any functional language to be able to give such a trace for any expression.