Yes, there are plenty of times I would not use recursion. Recursion is not free, it has a cost in stack space and that can often be a much more limited resource than some others. There's also a time cost, however small, in setting up and tearing down stack frames.
By way of example, the much vaunted factorial function is one where I would probably opt for an iterative approach where the numbers were large. Calculating 10000! with the Python:
def factorial (n):
if n = 1: return 1
return n * factorial (n-1)
will attempt to use a whopping 10,000 stack frames (though Python will protect you against this). The equivalent iterative solution:
def factorial (n):
r = 1
while n > 1:
r = r * n
n = n - 1
return r
will use just the one stack frame and precious little else.
It's true that recursive solutions are often more elegant code but you have to temper that with the limitations of your environment.
Your carbon
example is one where I would actually use recursion since:
- it uses at most six stack frames (one per character in the string); and
- it's relatively elegant, at least much more so than six nested loops and huge equality checks.
For example the following Python code does the trick:
def recur (str, pref = ""):
# Terminating condition.
if str == "":
print pref
return
# Rotate string so all letters get a chance to be first.
for i in range (len (str)):
recur (str[1:], pref + str[:1])
str = str[1:] + str[:1]
recur ("abc")
producing:
abc
acb
bca
bac
cab
cba
Of course, if your string can be 10K long, I'd rethink it, since that would involve a lot more stack levels but, provided you keep in low enough, recursion is a viable solution.