My first encounter with recursion was when I needed to traverse a directory tree. I couldn't figure how to go arbritrarily deep without writing tens of nested for-loops. Then recursion somehow hit me, or I found something interesting on Google, can't remember, it was over 10 years ago, pretty sure SO wasn't around.
...and then a while later I found out about os.walk (this was python).
import os
import os.path
def list_files_recursive(path):
filenames = os.listdir(path)
for filename in filenames:
fullname = os.path.join(path, filename)
if os.path.isdir(fullname):
yield from list_files_recursive(fullname) # recursively explore folders
else:
yield fullname
and here is the same program with an explicit stack import os
import os.path
def list_files_stack(path):
folders = [path] # create stack of unexplored folders
while folders: # repeat until stack is empty
path = folders.pop() # pick a folder from stack
filenames = os.listdir(path)
for filename in filenames:
fullname = os.path.join(path, filename)
if os.path.isdir(fullname):
folders.append(fullname) # push folder to stack
else:
yield fullnameThanks a lot!
Practical: If we right all of are programs and tail-recursive (returning a recursive call or constant at the end of the prgram) programs they are easy to transform into simple while loops with no stack. The idea is instead of calling another function just restart the current one with the updated arguments.
EX:
f(n,x)=f(n-1,x+1)
f(0,x)=x
goes to while(n > 0){
n--;
x++
}
Other techniques such as trampolining and continuation passing style also help translate recursive functions into iterative ones.Theorectical: Think about Brainfuck or Turing machines, these computing frameworks can compute any computable function using only what amounts to while loops and infinite memory.
Given then that we can produce arbitrary control flow using only while loops, we can reproduce how recursive calls are computed in computers with stack frames (provided by our stack).
You just won't get a stack overflow exception with the loop -- you'll run out of heap instead. It's still the stack filling up.