Recursion can be used in several different situations, but there are a few main ones. One is when you have a big problem and you need to know how to solve smaller problems of the same kind in order to solve the big problem. This is what we did in Assignment 1. When we had 8 cheeses and 4 stools, in order to move those 8 cheeses we found an i value (3) that told us how many cheeses to move (5). So we had to move 5 cheeses from one stool to another stool - but in order to do that we had to first move (5 - i) cheeses from one stool to another stool, and in order to do that...until finally, all we had to do was move one cheese from one stool to another. This problem of moving 8 cheeses was solved simply by knowing how to move one cheese, and repeating that 33 times.
Another situation is when you don't know how many items are in a list or how many times you'll have to repeat a process. An example of this is nested lists. A lot of the functions we wrote in class and also most of the functions in the Tree Class that we developed involved nested lists. Because we don't know to what depth the list is nested, we cannot use a for loop (where we would have to specify the number of items to go through.) A while loop cannot be used for similar reasons. The only way to solve this problem is to continue to call the function indefinitely, and to tell it when you want it to stop - this is called the base case. A recursive function always needs a base case and therefore usually needs an if statement; otherwise it will never stop calling the function.
Recursion is used a lot in computer science. Two simple examples of recursion are factorials and the Fibonacci sequence. A factorial (n!) is defined as (n x n-1!). This is a recursive definition, and the execution of this function would continue until n = 1, at which point it would execute the enclosing functions in reverse order. The Fibonacci sequence is a sequence where the next number is obtained by adding the two previous numbers (and the sequence starts with 1, 1). We could define a function for the nth term: fib(n) = fib(n-1) + fib(n-2). To find this, we would need to know the two previous terms, and hence their two previous terms and so forth, so we'll end up having to know the first two terms of the list. Both these functions are examples of the first use of recursion mentioned above.
Recursion is extremely useful. I have really enjoyed learning recursion so far and I hope that I will continue to enjoy it!
Have a good week everyone!
No comments:
Post a Comment