The last shall be first…in F#
One of the first things I used F# for outside of demo learning apps was some scientific data analysis. One of the desired results was looking for the first and the last occurrence in a set of data. My first attempt at this is pretty pathetic. Feel free to point and laugh at this late night approach.
I was trying to figure out how to get access to a specific element in a sequence. Since I wasn’t too familiar with the F# libraries I came up with a horrible but usable solution. This code didn’t need to be fast, which is good since there was an obvious performance issue. Using my limited knowledge of accessing data in a sequence I used Seq.head to take the first element. This solved half the problem. Now I just needed to get the last element in the sequence. For some reason I came up with converting the sequence to a list and reversing the list. Then I could take the head (first element) again and that one would be the last element. It was convoluted and I knew it but it worked and I was tired.
Then I recently re-watched http://channel9.msdn.com/Blogs/pdc2008/TL11 and something jumped out at me. Seq.nth. That little three letter bastard of a function. One thing I noticed about functional programming is that the discovery of methods/functions is a little different than in OOP. Instead of asking an object what it can do you have to interrogate some library and see if it can accept what you want to pass it. Enough excuses as to why I missed it. I was able to quickly encapsulate what I wanted with the following code.
I like this code much better. It feels much less like an ugly hack. It also follows more in line with functional programming where you specify what you want not how to do it. See http://www.infoq.com/presentations/Functional-Thinking for more information on functional thinking.
Thank god for refactoring.