Calculating the Fibonacci Sequence with C# 3.0
Scott Hanselman just posted his latest article in his weekly source code series. He shows various ways of producing the Fibonacci Sequence using various languages. I found it really interesting, for two reasons:
- I tried to do the C#3.0 one on my own after listening to a podcast about F#, and never could work it out. (Doh!)
- It makes me question what I thought about coding.
You see, I spend a lot of time refactoring. Sometimes too much. I have to ask myself why. It’s usually so that I can come back to the code later, and still understand what I was trying to do. Most of the time, conciser is better. But not always!
And that’s what I see in this post.
Suppose I had written this C# function (shamelessly stolen from Scott’s post):
Func<int, int> fib = null; fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Compare this to the C# 2.0 version:
static int Fibonacci(int x) { if (x <= 1) return 1; return Fibonacci(x - 1) + Fibonacci(x - 2); }
Apart from the fact that these methods actually give different answers (sorry, Scott), if I were to try to understand these methods 6 months after writing them, which one of the code samples would I be most glad of seeing again?
You see, most code only gets read again for two reasons:
- to debug it, or
- to hand it over to someone else
In both cases, clever though it may seem, the first conciser version would probably cause more trouble. Now, don’t get me wrong, I’m all for good concise code, but XSLT is concise, and I hate debugging that.
Now, considering that in order to reuse the Func<int, int> function, I would have to pass the around, thus holding it in a static variable, or wrapping it in another class, it doesn’t actually turn out to be that practical after all. Concise, yes. Practical and readable, hmm.
So, while we have a very-much-by-Ruby-On-Rails-driven trend going to make code as beautiful as possible, don’t forget to not go too far. We have to be able to read code later on, remember.
This is my personal blog, where I express my thoughts and thinking about programming and software development.
Nithiwit
31 Mar, 2008
the result of fibonacci is 0,1,1,2,3,5,8,13,21,…
when i input number 8, i want to output is 13 or input number 13 output is 21
Ps.help me please
awake
20 Feb, 2009
I’m sure you already found a solution by now, but all you need do is go the non-recursive route and your input is greater than the last number in the sequence calculated, get the next fib #.
http://www.brpreiss.com/books/opus6/html/page76.html