TL;DR : Do functional languages handle recursion better than non-functional ones?
I am currently reading Code Complete 2. At some point in the book, the author warns us about recursion. He says it should be avoided when possible and that functions using recursion are generally less effective than a solution using loops. As an example, the author wrote a Java function using recursion to compute the factorial of a number like so (it may not be exactly the same since I do not have the book with me at the moment):
public int factorial(int x) {
if (x <= 0)
return 1;
else
return x * factorial(x - 1);
}
This is presented as a bad solution. However, in functional languages, using recursion is often the preferred way of doing things. For example, here is the factorial function in Haskell using recursion:
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
And is widely accepted as a good solution. As I have seen, Haskell uses recursion very often, and I did not see anywhere that it is frowned upon.
So my question basically is:
- Do functional languages handle recursion better than non-functional ones?
EDIT : I am aware that the examples I used are not the best to illustrate my question. I just wanted to point out that Haskell (and functional languages in general) uses recursion much more often than non-functional languages.
factorial n = product [1..n]
is more succinct, more efficient, and does not overflow the stack for largen
(and if you need memoization, entirely different options are requires).product
is defined in terms of somefold
, which is defined recursively, but with extreme care. Recursion is an acceptable solution most of the time, but it's still easy to do it wrong/suboptimal.