I'm really interested in functional programming and I've been learning about it for a while a quite a while now but I've hit a subject which has left me stumped. That is recursion. I mean fucking hell, I can't figure it out! When I was learning how to code I was seeing nothing but for loops in other peoples code so that's how I do things. For loops everywhere! Hell I barely know how to use a while loop. Can someone tell me if there's a point to functional programming without recursion? Can you use iteration? Maybe you can explain recursion or link me to good examples because I sure haven't come across any.
Name:
Anonymous2011-06-05 0:01
Recursion is simply the act of a function directly calling itself from within that same function.
bool bar(int n) {
if(n > 0) {
return bar(n - 1);
}
else {
return true;
}
}
Recursion creates nesting: all previous iterations are self-contained islands on the stack and any variables available to the most current version of the function are unique (bar "pass by reference"). All previous iterations of the function remain valid and you will have to pass control back through them to restore normal flow control at some point. For example, the above code will call itself for as many integers above zero as is its initial input; ultimately, the input will be equal to 0 during one self-call, and the stack will unravel: bar(5)
bar(4)
bar(3)
bar(2)
bar(1)
bar(0)
true
true
true
true
true
true
true
Use recursion lightly. It creates stress on your stack due to the excess of frames that may be needed.