Recursive functions

These are weird and not always necessary. But sometimes can yield an elegant solution. Particularly when you have unpredictable data.

Let's review regular functions

Recursive functions are a case where you have to feed the prior values back into the formula or function. This is different from moving across a set of numbers and applying the same changes to each of the values.

For example: “write a function that adds 2 to any inputted value” would go over the number line and add two to each number.

| input  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8  | 9  | 10 |
|--------|---|---|---|---|---|---|---|---|----|----|----|
| output | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

We can know the value for any particular input with just that single input. No other values are needed. If the input is 4, we add two to it, and our result is 6.

Sometimes we can't do our calculations this way.

Recursive functions take an input and other parameters like any other function, but they have a special trick of using prior values of the function. For example: “add the two prior values” Of course it gets tricky when you try to consider where the function should start. This is why recursive functions need to include a base case. What is either the minimal unit for analysis or what is the starting point for the calculations to begin.

Recursive functions

One of the main differences with recursive functions is that their inputs come in from prior values. You cannot (generally) compute the value at a given moment without calculating prior stages.

It isn't always necessary to make a recursive function.

  • you could run through all the prior values within the function, without calling the function internally

  • you could use (if available) another formula that can correctly calculate the value without needing the prior values

Last updated