(So... it's been a while since I've updated my SLOG. I hope it isn't too late. DX)
Recursion is great! Before CSC148, the only experience I had with recursion had to do with Fibonacci numbers and fractals. Like with recursion ideas in computer science, trying to do things done with recursion without recursion is painful, and almost impossible. For Fibonacci numbers, defining them recursively looks like this: F(n) = F(n-1) + F(n-2), where F(n) is the nth Fibonacci number. Defining them non-recursively, however, requires radicals and the golden ratio (see: http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression).
Learning recursion in CSC148 is like learning a new way to think. Instead of thinking of a tree as a (real life) tree, recursion is more like thinking of it as broccoli; trim off a broccoli floret, and you get a mini broccoli! (Cutting a branch off of a tree doesn't really make another tree. Ok, I guess a branch is kind of shaped like a tree.) Recursion is thinking of every (computer science) tree as a collection of other trees.
Whenever I write a recursive function, I start with the base case (I'm sure everyone else starts here too). What if I had the smallest possible piece of a broccoli? Find the simplest tree and write code for that. What I forget to do a lot of the time, and what is really important, is remembering what it is the function returns. Maybe the function returns a list of ints, and the base case produces only an int - never forget to turn it into a list! Next, I think of the big broccoli, but rather than thinking of the broccoli just as broccoli, I think of it as a collection of smaller broccoli. What do I get out of the smaller broccoli, and how do I combine it? What really helps is thinking of each of the tree nodes, the child and the parent as essentially identical. I'm not entirely sure how to describe it, but, rather than thinking of the exact process, I think of what combines the two nodes, and then (most of the time) everything works out.
No comments:
Post a Comment