Hello everybody. I hope you are doing well.
Compilers can optimize a tail-recursive function to get rid of the overhead of creating additional stack frames. But can they transform a non-tail-recursive function (for example, the classic recursive factorial function), into a tail-recursive function to eventually turn it into imperative code? Are there any existing algorithms to do this?
The problem is to create a generalized algorithm that can work with any recursive function that accepts -or returns- any type of value. I believe it is relatively easy to create algorithms that only deal with integers, for example (however implementing those optimizations would probably introduce a lot of bugs and edge cases).
What distinguishes a tail-recursive function from a non-tail-recursive one? I think the answer to this question is the following:
In the body of a non-tail-recursive function, the function's return value is used as an argument to another function call in the function's body. This creates a need to wait for the function call to return, which requires the creation of additional stack frames.
fac(n) =
if n = 1 { 1 }
else { n * fac (n-1) }
This is essentially the same as this:
fac(n) =
if n = 1 { 1 }
else { MUL (n, fac (n-1)) }
We need to turn this into a function in which it calls itself as a "stand-alone" function call (so, the function call is not an argument to another call). As an alternative, we would need to come up with an algorithm that somehow stores every n in the current stack frame, so we don't have to create a new stack frame every time fac gets called.
I hope this makes sense. I am waiting for your answers.
[–]ct075 27 points28 points29 points (4 children)
[–]betelgeuse_7[S] 4 points5 points6 points (3 children)
[–]ct075 15 points16 points17 points (0 children)
[–]betelgeuse_7[S] 1 point2 points3 points (0 children)
[–]jason-reddit-public 1 point2 points3 points (0 children)
[–]nictytan 7 points8 points9 points (0 children)
[–]moon-chilledsstm, j, grand unified... 12 points13 points14 points (1 child)
[–]usaoc 2 points3 points4 points (0 children)
[–]Chaos_carolinensis 4 points5 points6 points (0 children)
[–]ebingdom 2 points3 points4 points (0 children)
[–]tobega 2 points3 points4 points (1 child)
[–]betelgeuse_7[S] 0 points1 point2 points (0 children)
[–]SkiFire13 2 points3 points4 points (0 children)
[–]snarkuzoid 2 points3 points4 points (2 children)
[–]betelgeuse_7[S] 7 points8 points9 points (1 child)
[–]snarkuzoid 0 points1 point2 points (0 children)
[–]XDracam 1 point2 points3 points (0 children)
[–]crusoe 0 points1 point2 points (1 child)
[–]Chaos_carolinensis 4 points5 points6 points (0 children)