Question

I doing something with a hierarchical data structure, and I've designed a group of methods to traverse/analyze it with indirect recursion as explained below.

There are methods a, b, c, and d, all with a Unit return type. Method a is called first. Depending on the data it will do something and then either halt or call one of b/c/d. Same thing with each of b, c, and d -- each method may either halt or call any of the other 3 methods. So which methods are called and their order of execution will be unknown until runtime, and the recursion is not directly apparent because no method is directly calling itself (don't worry, every method will be commented to describe the circular/recursive nature of the calls).

Each additional call to a, b, c, or d is the last thing to execute in each method, but it's not literally the last statement of each method; there will be an if or case statement that controls which one will be called.

Is the Scala compiler able to analyze this multi-layered call chain and implement tail recursion for it, given that no method is directly calling itself?

Was it helpful?

Solution

No, Scala is unable to perform that sort of tail-call optimization; the JVM doesn't really make this possible (or at least not easy).

You can mimic it yourself by writing one function that can take four different paths depending on arguments, however. (If the compiler were to help you out, it'd have to do something like this.)

OTHER TIPS

Although the compiler cannot do that automatically for you, your use-case should be amenable to use scala.util.control.TailCalls.

That won't be very performant though and if your calls are only going 4 deep, that may not be worth it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top