30 September 2018, 15:50

recursion


Recursion

Recurions is one of those topics in programming that I have had an interest in. Partly because infinate recursion is well... so weird. It reminds of me of the Eternal Return Theory.

However in code we have control of the boundaries and can stop the recursive call at anypoint. This can yield some interesting results

But first let's graple with what recursion actually is...

say we have a function:

function someFunction(){

}

and it calls itself:

function someFunction(){
    someFunction()
}

It would be known as a recursive call and is a technique for solving certain types of problems. A basic example is the factorial calculation.

The factorial of a number written as n!, n being the number.

4! = 4 * 3 * 2 * 1
3! = 3 * 2 * 1

the above can also be written as:

4! = 4 * 3!

Or in general terms:

n! = n * (n - 1)!

and finally in english:

_the factorial of n is defined as n times the factorial of n-1_

The english version defines factorial in the the definition of factorial. This self reference is a clue that the problem can be solved with recurion.

To illustrate the difference between a recursive implementation and a iterative one I am going to calculate the factorial of a number with a loop first:

Now here is a example using a recursive stragegy:

Notice there is no iteration, this is key.

Recursion is unusual at first but is really beautiful and can create some interesting patterns.

Here is a simple circle that recursively gets smaller and smaller until the radius equals two

See the Pen Recursive circle by Adam Harpur (@harps116) on CodePen.

This pattern is pretty trival and could be displayed using an iterative approach. Here is one that needs recursion to work. For every circle displayed draw a circle half it's size to the left and right of that circle.

See the Pen Recursive circles two by Adam Harpur (@harps116) on CodePen.

We a little more code we can draw a circle above and below aswell.

See the Pen Recursive circles four by Adam Harpur (@harps116) on CodePen.

Recursion is both elegant and useful and an important tool on the programmer's toolbelt.

Inspired by The Nature of Code by Dan Shiffman


← Gravitational Attraction
Steering Behaviour →