Enumerations and pattern matching in F#

Enumeration types in F# are declared using the pipe symbol. Each element will have an integer value. Here’s an example with the first 6 months of the year:

type MonthsInFirstHalf = January = 1 | February = 2 | March = 3 | April = 4 | May = 5 | June = 6

We select an element using the dot notation which is the same as in C# or Java:

let april = MonthsInFirstHalf.April

The more interesting language construct is the F# equivalent of the switch statements to check for the value of the enumeration. In F# it’s called pattern matching.

In C# we would write something like this:

switch (monthsInFirstHalf)
   case MonthsInFirstHalf.January:
   case MonthsInFirstHalf.February:
   //code ignored
       Console.WriteLine("Other month");

The F# equivalent uses the ‘match’ and ‘with’ keywords as follows:

let enumMatch month = 
    match month with
    | MonthsInFirstHalf.January -> printfn "Dark and cold"
    | MonthsInFirstHalf.February -> printfn "Still cold but more sunshine"
    | MonthsInFirstHalf.March -> printfn "Temperature mostly above 0, increasing number of hours with sunlight"
    | MonthsInFirstHalf.April -> printfn "Spring is here"
    | MonthsInFirstHalf.May -> printfn "Good times"
    | MonthsInFirstHalf.June -> printfn "Lots of sunshine"
    | _ -> printfn "Month not supported"

let e = enumMatch april

‘month’ will be of the enumeration type. The compiler will “know” that from the values after the ‘with’ keyword since we listed the values of the enumeration one by one. For each month we’ll print some short comment. Note the last entry with the underscore. That’s F#’s way of expressing “default”. Without this entry the F# compiler will emit a warning that not all enumeration types may have been accounted for.

Since we’re testing the matching function with April we’ll see “Spring is here” printed in the interactive window.

View all F# related articles here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: