Recursion

double [ ] = [ ] ✓

double [ F ... R ] = [ F * 2 ... double R ] ✓

F

R

F

double [ 1 , 2 , 3 ] = [ 2 , 4 , 6 ]

How do we put pattern matching on lists to use? To do this we must rely on a concept called "recursion", which basically means a function that refers to itself. The old programmer joke is that the definition ofisLet's say we want a function to double every number in a list, and you had to write it without using the apply ... to ... function we talked about previously.Firstly, what would such a function return if given an empty list? Obviously if there is nothing in the list to double, then it should just return an empty list:Here we're using a variation of the list pattern matching that we haven't seen before, [] will only ever bind to an empty list. In the terminology of recursion, this is our "base case".So great, we can now double every number in an empty list - not very useful. Here is how we define a function to double every item in a non-empty list:What's going on here? We take a list and break it into, the first item, and, the remaining items. Then on the right of the = we create a new list, with first element*2, and the rest of the elements are then doubled! This is the essence of recursion.You might then ask - "If this function calls itself, won't it keep going forever"? Fortunately not, because every time it is called it is with a shorter version of the list, until eventually it is called with an empty list, and our "base case" takes care of it. Let's try it out:While recursion is very flexible, and can be used to do something similar to the, and thefunctions mentioned previously, it isn't very efficient. It is much better to use one of these other list manipulation functions if possible.