Convert normal recursion to tail recursion

后端 未结 6 773
悲哀的现实
悲哀的现实 2020-12-13 07:30

I was wondering if there is some general method to convert a \"normal\" recursion with foo(...) + foo(...) as the last call to a tail-recursion.

For exa

6条回答
  •  别那么骄傲
    2020-12-13 07:49

    I'm pretty sure it's not possible in the simple way you're looking for the general case, but it would depend on how elaborate you permit the changes to be.

    A tail-recursive function must be re-writable as a while-loop, but try implementing for example a Fractal Tree using while-loops. It's possble, but you need to use an array or collection to store the state for each point, which susbstitutes for the data otherwise stored in the call-stack.

    It's also possible to use trampolining.

提交回复
热议问题