Cover photo by Ilija Boshkov on Unsplash
The last few months I've been trying to get my head around F#. If you'd like to start learning F# I can highly recommend Get Programming with F# by Isaac Abraham, especially when you have a background in C# like I do.
Today I've learned something about Discriminated Unions in F#. You use a DU when you have to model an is-a relationship.
But first things first, how does such a relationship look like in an object oriented language like C#?
public abstract class Animal { public abstract string Talk(); }
public class Dog : Animal { public override string Talk() { return "Woof!"; } }
public class Cat : Animal { public bool IsAggressive { get; set; } public override string Talk() { return IsAggressive ? "MEEEEEEEEOOOOOOOW!!!" : "Meow"; } }
// usage var dog = new Dog(); dog.Talk(); // Woof! var cat = new Cat(); cat.Talk(); // Meow var aggressiveCat = new Cat { IsAggressive = true }; aggressiveCat.Talk(); // MEEEEEEEEOOOOOOOW!!!
And now let's see the equivalent in F#:
type Animal = // base type | Dog // no custom fields | Cat of IsAggressive:bool // add custom field // add function with the help of pattern matching let talk animal = match animal with | Dog -> "Woof!" | Cat aggressive when aggressive = true -> "MEEEEEEEEOOOOOOOW!!!" | Cat _ -> "Meow"
// usage let dog = Dog dog |> talk // Woof! let cat = Cat false cat |> talk // Meow let aggressiveCat = Cat true aggressiveCat |> talk // MEEEEEEEEOOOOOOOW!!!
Pretty neat, isn't it?
What I really like about the F# approach is that I'm able to see the whole type hierarchy at a glance. Of course it's technically possible to put all C# classes into one file. But then you would certainly follow the "One class per file" convention ;-)
You can read more about Discriminated Unions on F# for fun and profit or Microsoft Docs.
Top comments (0)