Recursion in Functional Programming

Programming Paradigm Concepts

Eleanor Thomas

Senior Data Analytics Engineer

What is recursion?

  • Recursive function: a function that calls itself
  • Must contain a termination condition, or base case
  • Also contains the recursive call to itself with modified input
0 | def my_recursive_function(input_value):
1 |     # base case
2 |     if base_case_condition:
3 |        return base_case_output_value
4 |     # recursive call
5 |     else:
6 |        return my_recursive_function(modified_input_value) + some_modification
Programming Paradigm Concepts

Why use recursion?

  • Some problems are more straightforward when defined recursively
  • Fibonacci numbers:
    • 0, 1, ...
    • 0, 1, 1, ...
    • 0, 1, 1, 2, ...
    • 0, 1, 1, 2, 3, ...
Programming Paradigm Concepts

Some more examples of recursion

A file system

  • Searching through a file system
Programming Paradigm Concepts

Some more examples of recursion

A file system; a sorting method

  • Searching through a file system
  • Certain sort algorithms, such as Merge Sort
Programming Paradigm Concepts

Some more examples of recursion

A file system; a sorting method; a data structure

  • Searching through a file system
  • Certain sort algorithms, such as Merge Sort
  • Various data structures are defined recursively
Programming Paradigm Concepts

Recursion versus iteration

  • Every recursive function can also be written iteratively
  • Iterative function uses a loop rather than a recursive call
def iterative_factorial(n):
    result = 1
    for i in range(1, n + 1):
        result = result * i
    return result
Programming Paradigm Concepts

Let's practice!

Programming Paradigm Concepts

Preparing Video For Download...