English 中文(简体)
F# - Enumerations
  • 时间:2024-12-22

F# - Enumerations


Previous Page Next Page  

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 pterals to make code more readable and maintainable.

Declaring Enumerations

The general syntax for declaring an enumeration is −

type enum-name =
   | value1 = integer-pteral1
   | value2 = integer-pteral2
...

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