-5

So we just finished the subject recursion in school and I am still wondering "why?".

I feel like I have just learned a hell of a lot about math in a programming way with the sole purpose of passing an exam later on and then never again.

So what I want to know is when to use it? I can only find people saying "when you want to call a function within itself" but why would you do that?

Nulle
  • 1,301
  • 13
  • 28

1 Answers1

2

Recursion is the foundation of computation, every possible program can be expressed as a recursive function (in the lambda calculus). Hence, understanding recursion gives you a deeper understanding of the principles of computation.

Second, recursion is also a tool for understanding on the meta level: Lots of proofs over the natural numbers follow a pattern called "natural induction", which is a special case of structural induction which in turn allows you to understand properties of very complex systems in a relatively simple way.

Finally, it also helps to write good (i.e. readable) algorithms: Whenever there is data to store/handle in a repetitive calculation (i.e. more than incrementing a counter), you can use a recursive function to implicitly manage a stack for you. This is also often very efficient since most systems come with a machine stack at hand.

choeger
  • 3,562
  • 20
  • 33