1

I have seen these questions:

These all mention tail-call optimization. I am wondering though if, given a function such as what follows, it is possible to automatically "flatten" it from recursive to iterative, using something other than tail-call optimization (which I don't think applies in this case, and I wouldn't want to place that restriction otherwise).

a() {
  while x < 3 {
    b()
  }
}

b() {
  c()
}

c() {
  d()
}

d() {
  a()
}

Notice d calls a and starts the recursion over, but assume that it won't recurse forever, just a few levels deep (this is just pseudocode). This is different than the fibonacci example which just has 1 function recursively calling itself. I'm wondering if any research has been done on the topic of automatically converting complex recursive functions like this into iterative ones.

Lance
  • 75,200
  • 93
  • 289
  • 503
  • If there is, students, including me, no need to struggle with homework anymore! – Soner from The Ottoman Empire May 22 '18 at 00:45
  • 1
    For a while babel would convert simple tail recursive functions to a while-loop. They've since [removed this feature](https://github.com/babel/babel/issues/256) but [other examples](https://www.npmjs.com/package/babel-plugin-tailcall-optimization) exist. In short, yes a mechanical conversion is possible. – Mulan May 22 '18 at 16:35

0 Answers0