How is this recursive function automatically converted into iterative function?
I am reading on tail recursion as below
Tail recursion refers to a recursive call at the last line. Tail recursion can be mechanically eliminated by enclosing the body in a while loop and replacing the recursive call with one assignment per function argument.
For example
void print(Iterator start, Iterator end, ostream& out=cout) {
if(start == end)
return;
out << *start++ << endl;
print(start, end, out);
}
is converted to iterative by above specification as
void print(Iterator start, Iterator end, ostream& out=cout) {
while(true) {
if(start == end)
return;
out << *start++ << endl;
开发者_StackOverflow中文版 }
}
In above passage it is mentioned that "replacing recursive call with one assignment per function argument, but in given example we didn't have any assignment?
Can any one explain and provide example for above explanation about how to translate recursive to iterative function?
The assignment is hidden in the increment operator:
start++;
is in fact an assignment:
start = start+1;
Actually, the example (part one) is not very good.
out << *start++ << endl;
print(start, end, out);
should be
out << *start << endl;
print( start+1, end, out);
I don't think, whatever passage you are referring is important; just focus on the main problem, where you want to convert a recursive function to a normal iterative function, which can be done (effortlessly) as,
void print(Iterator start, Iterator end, ostream& out=cout) {
while(start != end) {
out << *start++ << endl;
}
}
It is hidden a little in C++, but start++
is assigning a new value to each time in the loop.
What they are talking about is, that you assign the arguments of the tail function call to the parameter variables of this function invocation, but in this case it is not neccessary, as you are calling the function with the exact same arguments (because like others said, the change to the first argument start
happened before the function call).
Actually, if done precisely, the iterative function should look like
void print(Iterator start, Iterator end, ostream& out=cout) {
while(true) {
if(start == end)
return;
out << *start++ << endl;
start = start;
end = end;
out = out;
}
}
But these assignments are completely unneccessary, even if conpectually correct.
The general conversion of recursive to iterative would look like this.
Original code:
void print(Iterator start, Iterator end, ostream& out=cout) {
if(start == end)
return;
out << *start++ << endl;
print(start, end, out);
}
Converted code:
void print(Iterator start, Iterator end, ostream& out=cout) {
while(true) {
if(start == end)
return;
out << *start << endl;
// One assignment per function argument for 'general' tail recursion
start = start + 1; // (1)
end = end; // (2)
out = out; // (3)
}
}
The three assignments as in the explanation are included. Assignment (1) is embedded in the start++
, assignments (2) and (3) are optimized away.
精彩评论