A function calls itself recursively is a recursive function. "Recursive" is totally different from "circular" which brought infinite loops. Therefore, I usually start with a simple base case who can stop the recursive function by returning something. Next, I write general cases by calling the function itself; at that time, we can either return final result or accumulate each one. The cases are separated by if statements as the whole function is operated once again, whereas in CSC108, we use while loop to stop repetition as codes run inside the function. Moreover, we always need to check the correctness and even the error of our recursive functions through paper and pencils because we are thinking them based on our understanding on what should our function do in various examples. It is acceptable for me to construct a basic structure of a recursive function at the beginning, and then revise to make it closer and closer to the correct answer. The reason of doing this is it is much easier to trace a recursive function to find out what I have missed than to think about some codes recursively which might start or end at nowhere.
Recursive functions simplify our codes regards to its efficiency(a function can be used for as many times as you want). We would write recursive function when we can find some patterns from short examples to longer examples. In fact it turns out to be operating same things over and over until the base case is touched, such as it becomes empty. Also, they are good at showing the idea of how the function would run based on the previous step. Therefore, the recursive function only need relatively short codes within a function. Thus, practicing more on recursion is necessary for me as it is hard and important which requires thinking deeply, and I believe it would helps programming a lot!
I think recursion is quite a useful tool. You just need to assume what you have written is correct and try to get the next result. Also base cases is important
ReplyDelete