F# Elegance

I'm a .NET (C#) MVP but have always had an interest in F#. Maybe it's because, being a object-oriented developer, I tend to think of solutions as nouns interacting with each other as verbs. But in F# and other functional languages, it's more of a verb-first approach - kind of an inside-out approach to a problem.

Over the years, though, I've grown to appreciate this approach, probably as I've worked more with CQRS-style solutions and approached projects from a task-oriented approach.

But programming in a functional language has always been a hurdle for me, but I continue to try to clear the hurdle.

This past weekend proved an opportunity for a little F# workout. During the family post-Thanksgiving meal discussions, a deck of "Christmas trivia" cards were broken out. It became fairly competitive between myself and a few in-laws. One question that posed a problem was:

What is the total number of presents received if you received all of the presents in "The 12 Days of Christmas"?

Well, we all kind of stared at each other, thinking "Is it a factorial?", or "Is it a sum of squares?" Maybe it was the wine (well, it probably was), but our solution devolved into a guessing game with the questioner responding with "Higher" or "Lower". The final answer, 364, was arrived at, but we all felt that it wasn't a real answer.

Well, the next morning I was thinking about the problem as I was reading some tech blogs. I came across an article on F# and decided to tackle the problem using F#. It was so easy and elegant:

let rec daysofChristmasGifts n sum =
if n < 1 || n > 12 then
    sum
else
    daysofChristmasGifts (n-1) (sum + ([1..n] |> List.sum))

daysofChristmasGifts 12 0

So easy and elegant. I was thinking about the typical solution in C#, and while it would be easy to solve, it would be a bit clunky and loopy.

But treating functions as truly first class along with powerful functionality around handling lists and sets of data, makes F# a powerful weapon in a developer's toolbelt.