Project Euler and functional C#
I think I already talked (a long time ago) about Project Euler: a set of problems, mainly math oriented, keen to be solved with a computer program. To be sure, it's not particularly deep math, but the problems posed go fairly quickly from really easy, to hmm, to challenging. In this sense, they are good programming calisthenics, and may also be a good way of learning a new language. For example, Chris Smith has solved some Project Euler problems using F#, I find the idea intriguing, so I'll try to do the same thing, only that I'll be using C#, but not your plain old C# mind you, as I'll do my best to use in as much as possible the functional facilities of C# 3.0. Let's see for example Problem 1:
Add all the natural numbers below one thousand that are multiples of 3 or 5.
Ok, ok, the problem is silly trivial, but wait until you get to Problem 10 ;-). One C# 3.0 functional solution is:
Enumerable.Range(1, 999).Where(n => n % 3 == 0 || n % 5 == 0).Sum()
Range() generates the sequence from 1 to 999, and then Where() filters it leaving just the numbers multiples of 3 or 5, finally Sum() adds up these numbers. Easy, isn't it? And without loops or ifs.
Obviously, not all problems lend so naturally to be solved in a functional way, and we'll find out step by step how useful is the functional paradigm in Project Euler.