Enumerations and pattern matching in F#
March 25, 2017 Leave a comment
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: Console.WriteLine("January"); break; case MonthsInFirstHalf.February: //code ignored default: Console.WriteLine("Other month"); break; }
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.