When you consider the age old problem of representing different shapes (circle, triangle, square, rectangle, etc.) my OO fed developer brain naturally jumps to a class hierarchy along the line of:
This is perfectly fine and legit, but it’s not the only way to approach things. Since I’ve been on a more varied diet of programming paradigms I’m much more open to the idea of using F#’s discriminated unions to represent hierarchical data.
Discriminated union is a fundamental type in function programming, and for C# developers, think of it as an Enum with strongly typed names where the names don’t have to be of the same type. Using discriminated unions, you can rewrite the above code as:
And to test it, let’s create some shapes and workout their respective areas:
Was that more difficult than its C# counterpart? Not at all, in fact, I’ve littered the F# code with comments and still ended up with near half as much code! Check out my solution for project euler problem 54, a working poker hand evaluator in 100 lines of code , pretty sweet
That said, class hierarchies are great at modelling real world entities and they allow you to capture commonalities and shared behaviours, if done correctly they can remove duplicated code and reduce defects.
Discriminated unions on the other hand, are a great fit for hierarchical data structures such as binary tree, and for small hierarchies it requires little overhead in setting them up so it can give you a nice productivity boost.
Whilst I’m not suggesting that you should start converting all your class hierarchies to discriminated unions, I think there is a lot of value in having it in your toolbox nonetheless. The more tools you have at your disposal the better, being able to use the right tool for the right task beats hammering a screw in my opinion!
Subscribe to my newsletter and get new contents delivered straight to your inbox :-)