F# Revisited

Sometime last year, I wrote an article demonstrating BDD with C# and F#. The accompanying source codes were hosted on github.

Now I’ve been doing some more functional programming recently and took an opportunity to revisit the F# code I had written then. As it turns out, I had written the first version in Object oriented style in F#. Switching to functional style has made it even more elegant and concise. The difference – 55 lines of code, versus 120 earlier (versus some 200 odd lines of code in C# for the same functionality).

Some of the differences –

  • Using Records instead of Types to encapsulate data (e.g Date)
  • Using base types directly wherever it makes sense (for e.g. int for Year instead of a separate Year type)
  • Using independent functions rather than enclosing them within types

These three go together – functions as first-class citizens means that we no longer need to define types just to house them.

  • Using simpler syntax – for instance, avoiding unnecessary braces
  • Using more powerful language features – using type inference, pattern-matching, higher-order functions a lot more aggressively
  • Some cheating Smile – smaller variable names, fitting more on one line (both, only where it doesn’t affect readability).

I find the new version a lot simpler to understand, with very little distractions such as instantiating objects or trying to access their properties.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax