This Function is Not Tail Recursive
Tail recursion seems to be an easy concept, but most people get it wrong – including me. Reading the latest German Java SPEKTRUM, I’ve found an article about parallel multicore development by Kornelius Fuhrer. One paragraph was about functional development and tail recursion. First he claims tail recursion makes functions 100% parallizeable (I guess broadly speaking all compositions h(g,f) of side effect free functions g,f are 100% parallizeable in f and g, nothing to do with tail recursion) then he claims his example functions are tail recursive:
Wikipedia says about tail recursion:
In computer science, tail recursion (or tail-end recursion) is a special case of recursion in which any last operation performed by the function is a recursive call, the tail call, or returns a (usually simple) value without recursion.
In all three examples the last operation performed is the multiplication (*), not the function call to itself. First the function itself is called, then the return value is multiplied by n. Stackoverflow has a lot to say about tail recursion too.
A tail recursive version of factorial might look like this:
So please, do not call all functions where the last function call in your source code is a call to itself, tail recursive. A function is tail recursive, if the last operation is a function call to itself.
You can leave a Reply here. Of course, you should follow me on twitter here.
Haven’t read the article, but that would be quite embarrassing.
Anyway, just wanted to add, that tail recursion generally is more efficient than non-tail recursive functions, because ressources don’t have to be maintained over the recursive calls – at least in theory. On the JVM there will be created a new stack frame on each call, because tail recursion is not supported very well. On the other hand, the Scala compiler has tail call optimization and basically would turn the calls into a while loop.
Read my blog post on this topic, if you like http://stronglytypedblog.blogspot.com/2009/08/scala-tail-recursion.html