When a recursive procedure is divided among two functions that call each other, the functions are said to be mutually recursive. As an example, consider the following definition of even and odd for non-negative integers:

  • a number is even if it is one more than an odd number
  • a number is odd if it is one more than an even number
  • 0 is even

Using this definition, we can implement mutually recursive functions to determine whether a number is even or odd:

1def is_even(n):
2    if n == 0:
3        return True
4    else:
5        return is_odd(n-1)
6
7def is_odd(n):
8    if n == 0:
9        return False
10    else:
11        return is_even(n-1)
12
13result = is_even(4)
Step 1 of 18
line that has just executed

next line to execute

Mutually recursive functions can be turned into a single recursive function by breaking the abstraction boundary between the two functions. In this example, the body of is_odd can be incorporated into that of is_even, making sure to replace n with n-1 in the body of is_odd to reflect the argument passed into it:

>>> def is_even(n):
        if n == 0:
            return True
        else:
            if (n-1) == 0:
                return False
            else:
                return is_even((n-1)-1)

As such, mutual recursion is no more mysterious or powerful than simple recursion, and it provides a mechanism for maintaining abstraction within a complicated recursive program.

Video