F# – Enumerations


F# – Enumerations


”;


An enumeration is a set of named integer constants.

In F#, enumerations, also known as enums, are integral types where labels are assigned to a subset of the values. You can use them in place of literals to make code more readable and maintainable.

Declaring Enumerations

The general syntax for declaring an enumeration is −

type enum-name =
   | value1 = integer-literal1
   | value2 = integer-literal2
...

The following example demonstrates the use of enumerations −

Example

// Declaration of an enumeration.
type Days =
   | Sun = 0
   | Mon = 1
   | Tues = 2
   | Wed = 3
   | Thurs = 4
   | Fri = 5
   | Sat = 6

// Use of an enumeration.
let weekend1 : Days = Days.Sat
let weekend2 : Days = Days.Sun
let weekDay1 : Days = Days.Mon

printfn "Monday: %A" weekDay1
printfn "Saturday: %A" weekend1
printfn "Sunday: %A" weekend2

When you compile and execute the program, it yields the following output −

Monday: Mon
Saturday: Sat
Sunday: Sun

Advertisements

”;

Leave a Reply

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