Recursion is a kind of arithmetic which we call itself in its function body. It is the most difficult concept which I have learnt because it's sometimes difficult to trace a recursion, not to mention we write it ourselves.
The way I solve this problem and try to understand recursion is practice! After going through all of the lab materials and additional problems, I am much more familiar with recursion.Frankly speaking I go on well with assignment 2!
There are some thing we need to take care when we write a recursion.
1. we need a base case. Without a base case , a recursion function will run forever.
2. for a base case, we need return a value. Only in this case we can call the base case in more complicated situation.
3. the list expression [ fun(x) for x in ] is quite useful in recursion.
However,is there some patterns for writing recursion?
YES!
I used to follow the following steps.
1.I consider the base case. Regard the object as the simple way and return the expected value.("if expression")
2.Just have a try! Write the "else" expression using the base case! then you have to design a complicated example and trace it. You may fail in the first few times. But I always get it in the end.
Here is a example .
Here is a example .
For function sum_list,
1. we consider the base case.(ie. 1) then sum_list(1) = 1
so we write "if expression" as following:
2.we write the "else expression".
First I try like this:
But after tracing a few complicated example, I realize that this obvious wrong because we return a list! so we add "sum"! then we get it!
In summary, after few week's studying, recursion is not that difficult for me and it is a quite efficient way to solve problems of different depth.




cute patric star ;P
ReplyDelete