F# – Use Discriminated Unions instead of class hierarchies

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:

image

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:

image

And to test it, let’s create some shapes and workout their respective areas:

image

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 sweetSmile

Closing thoughts…

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!

4 thoughts on “F# – Use Discriminated Unions instead of class hierarchies”

  1. I think the key to choosing correctly between class hierarchies and unions is extendability by outsiders. If you want to allow that without forcing them to modify your code, then class hierarchies are the way to go.

    Unions are attractive when used in conjunction with pattern matching, as the compiler tells you if all cases are handled.

    It’s also easy to add new cases to a union, no ceremony involved. With classes, one often finds oneself shoe-horning new subclasses into interfaces that are seldom exactly what you would like them to be.

  2. Pingback: F# – Enums vs Discriminated Unions | theburningmonk.com

  3. Pingback: F# – Serializing F# Record and Discriminated Union types | theburningmonk.com

  4. Pingback: Here Be Monsters – Message broker that links all things | theburningmonk.com

Leave a Comment

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