Skip to content

Instantly share code, notes, and snippets.

@davesque
Created May 20, 2013 04:54
Show Gist options
  • Save davesque/5610488 to your computer and use it in GitHub Desktop.
Save davesque/5610488 to your computer and use it in GitHub Desktop.
Simple illustration of recursion as it is sometimes used in functional languages
# Again, these are contrived examples, but they do a slightly better job of
# illustrating the use of recursion in functional languages when no concept of
# program state is available.
# Notice that the if statement in the functional example 1 includes an else
# statement. This makes it more like a mathematical expression (because it
# causes the function to always return a certain value). Functional example 2
# uses a syntax available in python that truly is an expression built with if
# and else statements.
def add_imperative(n):
"""
Adds one to a total `n` times in the style of an imperative language.
"""
total = 0
for i in range(n):
total += 1
return total
def add_functional_1(n):
"""
Adds one to a total `n` times in the style of a functional language.
"""
if n == 0:
return 0
else:
return 1 + add_functional_1(n - 1)
def add_functional_2(n):
"""
Adds one to a total `n` times in the style of a functional language.
"""
return 0 if n == 0 else 1 + add_functional_2(n - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment