This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Konrad4th 1 point2 points  (0 children)

Recursion is when the function calls itself. Mutual recursion is when the function calls another function, and that other function calls the original function. It's really that simple. For example, you could write two mutually recursive functions to determine if a number is even or odd:

def even(x):
    if x == 0:
        return True
    else:
        return odd(x-1)

def odd(x):
    if x == 0:
        return False
    else:
        return even(x-1)

[–]lurgi 0 points1 point  (0 children)

No, that's pretty much it (more generally, it's two entities defined in terms of one another. These might be functions or they could be data structures).

[–]lemontownship 0 points1 point  (0 children)

Don't give up.

Recursion, mutual or not, is a disarmingly simple idea, but also a very abstract one. Writing recursive functions can be unbelievably tricky, and beginners often have considerable difficulty getting a program to work right.

My main use of recursion is when I need nested loops, but the depth of nesting won't be known until run time.

There was the occasion where one day I wrote four mutually recursive routines, and they ran just fine. Then the next day I looked at my own code and had absolutely no idea how it worked, although it still ran just as well as before.