Tail recursion refactoring

Hi, looking for some expert advice: is it possible to transform a loop like the following into a tail recursive one?

def loop(foos: List[A], acc: Map[Int, B]): Map[Int, B] =
  foos
    .map(foo =>
      val newFoos = f(foo)
      val newAcc = g(foo, acc)
      loop(newFoos, newAcc)
    )
    .fold(acc)(_ ++ _)

The function is working fine. But the loop is not iterating on itself, it has to iterate on a collection, each item generating a new collection, and then assemble the result. Is tail recursion achievable?

Hello,

It is possible to transform to a tail recursive, although sometimes it’s difficult and makes the code more complicated to read and understand.

One option is to use continuations and continuations passing style.
Or manage your own call stack, and transform it a la iterative

Hi @qqupp thank you for the tips. Motivated by your answer, I found this article On Recursion, Continuations and Trampolines - Eli Bendersky's website and I enjoyed its focus on beginners and examples, so I share it here. I will try to dig deeper into a possible refactoring. Thank you, Mario