When to use recursion? What is the cue when you have to use recursion?
Suppose I am to write a program that computes a factorial or checks if a string is a palindrome or prints all numbers from a certain range? I could use loops for those but I could use recursion?
What's the advantage of either? Is there something that recursion could do that loops could not?
Name:
Anonymous2013-09-06 8:34
recursion is just neat tricks that go down the toilet when you stack overflow (which happens in all but a few lisp dialects)
Name:
Anonymous2013-09-06 8:46
Recursion makes solutions far cleaner at times. More easily dynamic. With tail-recursion, which is supported by most compilers nowdays, and in things like Scheme, there's no penalty due to stack overflows or function calls.
Name:
Anonymous2013-09-06 8:57
>>3 this crashes here int rec(int i){ return rec(i); }
Recursion is required to deal with nested structures, such as trees. Furthermore, functional programming language fetishists have a strong dislike for loops because they require state management (temporary loop variable) and thus will always consider recursion cleaner.
Name:
Anonymous2013-09-06 9:12
>>4 It is optimized away, for me: --> cat rectest.c int rec(int i){ return rec(i); }
int main(){ rec(1); }
--> clang -O3 rectest.c -o rec; ./rec -->
Changing it to:
#include <stdio.h> int rec(int i){ putchar((i%26)+'a'); return rec(i+1); }
int main(){ rec(1); }
It never terminates: --> time ./rec > /dev/null ^C ./rec > /dev/null 29.45s user 0.08s system 99% cpu 29.598 total
Here's the generated ASM, it even labels the tail recursion:
Ah, looks like the code segment was the same either way. I suppose it inlined the function as well. Either way, it becomes a non-conditional jmp to after the function entry so the stack isn't touched.
Making it simpler, without libc calls: extern n(int i); int rec(int i){ n(i); return rec(i+1); }
>>9 Then you should only use recursion for recursive data structures and when a recursive function is shorter than the respective loop (assuming you don't need a break statement).
If your language supports tail call recursion, recursion can be pretty useful. Once you start doing anything at scale though, recursion falls apart. You'd probably want to try trampolining instead.
Name:
Anonymous2013-09-07 12:55
Been a while since I've had to look into it, but don't the fastest sorting algorithms still use recursion?