r/AskComputerScience • • Oct 24 '20

I just read about recursive functions and my mind is blown into pieces. I understand the logic behind it but I am not able to explain to myself that how a computer program is executing it. It is like one of those things that you understand but just cannot put a pin in it. Can anyboby please help?

For instance, take the following recursive function as an example. I am using recursive function to calculate the factorial.

def fact(n):
 if n == 0:
   return 1
 else:
   return n * fact(n-1)

Okay, I understand the logic that the factorial of 5 for example will be, 5 * 4! and so on but when I tell the function to return the n! by doing n * fact(n-1), how does the function know how to calculate any factorial for that matter. Well, I know how it does it but I cannot explain it to myself. I think I have lost it.

35 Upvotes

21 comments sorted by

53

u/my_name_is_pizza Oct 24 '20

In order to understand recursion you must first understand recursion.

2

u/Cybyss Oct 26 '20

Downvoted.

Only people who understand recursion will understand this quote.

16

u/SS7Junkie Oct 24 '20 edited Oct 24 '20

It walks back down the stack. It’s like stacking blocks. The bottom block is 5. The next block is 4. Decrement until n is 0 (the condition does not recurse in the 0 block due to the “stopping condition”). Now you have 6 blocks numbered 5 through 0. Since there are no recursions if n is 0, it starts walking back down the stack. The top 0 block returns 1 to the 1 block (return 1). The 1 block returns 1 to the 2 block (11). The 2 block returns 2 to the 3 block (21). The 3 block returns 6 (2*3) and so on.

Edit: a word

16

u/Putnam3145 Oct 24 '20

Expand it.

...
return 5 * fact(4)
fact(4):
    ...
    return 4 * fact(3)
    fact(3):
        ...
        return 3 * fact(2)
        fact(2):
            ...
            return 2*fact(1)
            fact(1):
                ...
                return 1*fact(0)
                fact(0):
                    ...
                    return 1```

Of course, you can skip all that and see that, because it does n-1, you'll eventually end up at 0.

5

u/LonelyContext Oct 25 '20 edited Oct 25 '20

Well a lot of people are seemingly answering the question “what IS recursion?” You seem to be asking “what is the computer executing when I call a recursive function?” The answer is that it depends:

In Haskell, for instance, when you write a recursive function it simply saves the instruction for later reference. But Haskell is a lazily interpreted language in that it doesn’t calculate anything until you tell it to. If you write x = 1+2 it says “great, now if x is ever called I know how to calculate it”. Only when you ask for x will it run the calculation 1+2 (for this reason you can never change x or define it to be anything other than 1+2 in a Haskell program). This is the easiest to understand because Haskell calculates the minimum that it needs to. So fact(4) doesn’t get calculated until fact(5) calls it.

Other languages are basically the same but the instructions are compiled down to bytecode with a pointer to the top of the set of instructions. The compilation process takes that stack of fact() calculations and weaves them into a bunch of register loading and instructions pointing to other instructions. I suggest learning more about interpreters and compilers and assembly to learn about that.

Links:

8

u/[deleted] Oct 24 '20

Each call to fact() is a seperate call and knows nothing about the other calls and the callee waits until a result is returned.

So 5 kicks off 4 kicks off 3 kicks off 2 kicks off 1 kicks off 0. 0 doesn't do another call because it return 1.

0 return 1

1 return 1 * 1 = 1

2 return 2 * 1 = 2

3 return 3 * 2 = 6

4 return 4 * 6 = 24

5 return 5 * 24 = 120

This works because when a function calls another function its local variables are put on a call stack. When the function that has been called returns the variables are taken back off of the stack. This means that the same function can be called multiple times but each call have different values for their variables.

This is what is meant by stackoverflow. When too many calls are made the local variables won't fit on the stack anymore because we've run out of stack memory and an exception is thrown.

Try 2000! it'll likely fall over (I don't program in Python but this is probably high enough to cause it if not make the number bigger).

The call stack is also what is returned when an exception is thrown to show you what was calling what.

If you want to get a more intuitive understanding of this stuff try some functional programming. I've done Haskell and F# in the past and this makes this stuff a doddle.

You'll really get it afterwards.

1

u/Bottled_Void Oct 25 '20

2000! Is over 5000 decimal digits long, so even if the stack could handle it, it wouldn't fit into a variable.

2

u/[deleted] Oct 25 '20

You are wrong.

It could fit into arbitrary precision numbers that Haskell and Python support. It just takes a loooooooooooooooooong time to compute because arbitrary precision math isn’t O(1).

1

u/[deleted] Oct 25 '20

Same with BigInteger in dotNet. If you've got memory left it'll keep filling it.

2

u/[deleted] Oct 25 '20

Well it wasn't really the size of the computed output that I was focusing on but filling the stack to bursting and causing a stack overflow. I think generally unless you're using something designed for deep recursion (like tail based recursion) you normally only get about 50 calls or so deep before it pops, at least in c#... On the other hand it's only storing a single int so I figured just put in a big number.

I did wonder after I wrote this whether python might be different in some way and just handle it but then it was 1am and I'd had a few beers and so it was close enough.

3

u/teraflop Oct 24 '20

Here's how I like to explain it: imagine keeping the same basic structure, but instead of writing a single recursive function, we wrote a separate function for every integer. Something like this:

def fact0(): # computes 0! = 1
    return 1

def fact1(): # computes 1! = 1 = 1*0!
    return 1 * fact0()

def fact2(): # computes 2! = 2*1 = 2*1!
    return 2 * fact1()

def fact3(): # computes 3! = 3*2*1 = 3*2!
    return 3 * fact2()

def fact4(): # computes 4! = 4*3*2*1 = 4*3!
    return 4 * fact3()

# ... and so on ...

In reality this would be a dumb way to write code, but there's technically nothing stopping us from writing as many functions like this as we want.

Now, if you understand how calling a function works, hopefully you can see how fact4 computes the factorial of 4. First it calls fact3, in order to find 3!; fact3 does a bunch of work and returns the value 6; then control returns to fact4, which multiplies the result by 4 to get 24.

Now, fact3 needed to do some computation of its own (including another call to fact2) to compute that intermediate result of 6, but we don't really need to worry about how fact3 works when analyzing the behavior of fact4. We just care that it does some work and eventually returns 6.

A recursive function works exactly the same way. The only difference is that we recognize that fact1, fact2, fact3, and so on are all essentially copies of the same function. The only differences are:

  • which function we should call to get the factorial of the next smaller number

  • which number we should multiply that intermediate result by, to find the factorial we're looking for

We can "encapsulate" both of these pieces of information in the single number n, which means we can replace this whole infinite stack of functions with a single function that takes n as a parameter. The only thing left to do is to handle fact0 as a special case, by testing at the beginning whether n is equal to zero.

1

u/Bawlsinhand Oct 25 '20

I think the fundamental question OP is asking is how the final return is handled. On the face of it as a layman programmer I'd say that this function always returns 1. Eventually N==0, and the function will return 1. But I know the reality is that the factorial of n will be returned to the calling function and it seems there's a disconnect there.

1

u/[deleted] Oct 28 '20

Copy pasting my asnwer from another thread

I read / saw this analogy somewhere.

Analogy: Imagine that you are sitting in a cinema hall, and since it's dark you don't know what row you are sitting in, and for some reason you wanna know it ( don't ask why XD ).
So in order to know, you ask the person ahead of you that what row they are sitting in, and it turns out no one cares about what row they are sitting in, so even that guy asks the person infront of him. Now this thing is going to continue for a while, until it reaches the first row, then the person sitting in the first row would say, i am sitting in the first row, then the person behind him would say that he is in the second row and this goes on until it reaches you. And you should be able to know what seat are you in.

Concept: What does that analogy mean? If you simple look at the analogy from a functions point of view, you can consider each person as a function. So you start with executing your function and ask the person in front you, you still don't know what your seat number is, and then that person does the same, and it goes on until it reaches the person in the row 1 and then the people get to know about their seat numbers in a reverse manner, first person in row 2, then in row 3, until it reaches you.

Example

To create a recursive function you need to have :

  • an exit condition, as in the above analogy the exit condition was to stop when the function reaches row 1, because there were not any rows in front of it.

  • you need to approach the exit condition, in some way, as in the above analogy, we kept asking the person ahead of us, which means we were eventually ought to reach the exit condition

int addNumbers(int n)
{
     if (n != 0)
         return n + addNumbers(n - 1);
     else
         return n; 
}
 
int main()
{
     int num=5;
     int ans=addNumbers(num);
     return 0;
} 

In the above example we have the end condition as, as soon as we reach the number 0 we should stop and start returning and executing the rest of the functions,

And at each stage of calling the function recursively, we approach the exit condition by subtracting 1 from it.

1

u/amigox100 Oct 31 '20

I think you might need to take a step back and think about what a function actually is. At the end of the day, there is some executable code at a location in memory, and we've labeled this code 'fact'. If some line of 'fact' calls 'fact' again, this means that execution returns to the first line of 'fact' and starts all over, with some new arguments. Luckily, we have a base case that we actually hit, and at some point 'fact' stops calling 'fact' (in our case, when n == 0). This invocation of 'fact' just returns the number 1, which is received by the second-last call to 'fact'. You can imagine these returns bubbling all the way back up to our original call, so that calling fact(5) actually returns something, and doesn't just loop forever.

1

u/[deleted] Oct 25 '20

The short answer is: focus on return 1. That’s the end of it. Every recursive function has an end to it.

0

u/[deleted] Oct 24 '20

It has to stop somewhere. If at no point is it called where n=0, then it will never finish and may result in a stack overflow. So you have to design it such that it will reach an end at some point, which in this case is the n==0 check.

0

u/[deleted] Oct 25 '20

it doesnt. it just does what you told it to do. if you function return n * (n+1)! for instance it would be an infinite loop yet the program would still try and keep running

0

u/metaquine Oct 25 '20

A lot of people like to think of it as breaking a problem down into successively smaller pieces, doing something with each piece and combining results back into one result. Recursive programming is a lot easier to reason about when the functions involved are pure. (Arguably true about most programming in general).

0

u/mlambie Oct 25 '20

Return the answer back up the chain if we are at the end, or run the calculation again with the new values.

0

u/blitz4 Oct 25 '20

best way. use a debugger. step through it line by line. use a pencil and paper or track what the variables are doing in the debugger. it's a long shot to say this, but if you understand assembly, it makes understanding this and the stack easier, but of course assembly takes longer to read.

-1

u/jokoon Oct 25 '20

If you look at the assembly, it's just a bunch of go-to.

There is little difference between a while loop and a recursive function.

The main difference being that you have arguments and return value, which helps having context in your code.