Recursion is something I have always struggled with understanding. I hope I can get some assistance here on how this function works. It works but I want to know how:
fibStep :: (Int,Int) -> (Int,Int)
fibStep (u, v) = (v, u+v)
fibPair :: Int -> (Int,Int)
fibPair n
| n==0 = (0,1)
| otherwise = fibStep (fibPair (n-1))
Recursion works much like a loop. With a loop you have a stop condition, and the same is true for recursion, except it is called the base case. In this Fibonacci example, the base case is
n==0, which returns the tuple(0,1)— and of course this represents the first Fibonacci number.After you’ve established your base case, now you need to figure out the recursive step — in this example it is
fibStep (fibPair (n-1)). This is equivalent to the code block for a loop, or what step is repeated on every iteration until the base case has been reached. Naturally, it is critical that you make sure you always converge to your base case, else the recursion will never end — and in the example, the recursive step does converge to the base case, because for each consecutive step, the value ofndecreases by one, meaning we must eventually reach the case wheren==0(assumingnis initially positive).Let us look at the evaluation of
fibPair 3. Each consecutive line is an expansion of the previous, using the definitions provided in the example.Importantly, you should become comfortable with an English explanation of what is happening.
fibSteptakes a tuple of(fib number x, fib number x+1)and returns the next tuple in sequence, namely(fib number x+1, fib number x+2).fibPairacts as loop overfibStep, causingfibStepto be calledntimes on the same tuple, meaning the tuple(fib number x, fib number x+1)will result as(fib number x+n, fib number x+n+1).Hopefully that helps clarify things a little bit. Recursion is truly just another way to write a loop; it has all of the same elements yet is written a bit differently. For some problems using recursion results in much simpler logic, or code, or both. Once you become more comfortable with recursion it will be a very useful tool to have for your future programming.