Pages

Friday, January 21, 2011

functional programming to find sequential group

It is Friday night and maybe some blog can help me relax a little bit.

If I got a input sequence like { 1, 2, 3, 6, 7, 8, 11, 12, 13, 145 },  how can you group them into some group where each group only contain continuous numbers. 

Please do not use for-loop, try to think the input like a single unit, a output from a function. Here is the solution:

 
var groups = input.Zip(Enumerable.Range(1, input.Length), (i, n) => new { i, GroupNumber=n-i }).GroupBy(m => m.GroupNumber, m => m.i);

how does think work? 

It use another continuous output as mirror to help group the input.

I found the way to write a good LINQ query or thinking in functional way is to compare the input and output and trying to find the different. You always think the input as a whole entity. After applying some functions, can easily prove the whole program is correct or not. that's the beauty of functional. I do not know a way to make a FOR loop into a nice math formula, maybe that's why I am always afraid of FOR loop.

The above sample give me a new way to design functional program by introducing another sequence or entity. I love functional!