F# Enumeration
Enumerations in F# are a user-defined type that allows you to define a set of named constant values. An enumeration can be defined using the enum
keyword.
Syntax
The syntax for defining an enumeration in F# is as follows:
type enumTypeName =
| Value1 = value1
| Value2 = value2
| Value3 = value3
...
enumTypeName
is the name of the enumeration typeValue1
,Value2
,Value3
are the named constants of the enumerationvalue1
,value2
,value3
are the integer values associated with the named constants
Example
type Color =
| Red = 1
| Green = 2
| Blue = 3
let color = Color.Red
printfn "%A" color
Output
Red
Explanation
In the example above, we have defined an enumeration type named Color
with three named constants: Red
, Green
, and Blue
. The integer values associated with each of the named constants are 1, 2, and 3 respectively.
We then declare a variable color
of type Color
and assign it the value Color.Red
. When we print the value of color
using printfn
, it prints the name of the named constant Red
.
Use
Enumerations are primarily used to improve code readability and maintainability. Instead of representing values using integers or strings, we can use meaningful named constants.
Enumerations are also useful in switch statements and pattern matching expressions to handle different cases.
Important Points
- Enumeration values are 32-bit integers by default
- You can explicitly set the integer value of an enumeration value
- The order in which the named constants are defined determines their integer value. The first constant has a value of 0, the second has a value of 1, and so on.
Summary
In F#, you can define an enumeration type using the enum
keyword. Enumerations are a useful way to define a set of named constants that improve code readability and maintainability. They are primarily used in switch statements and pattern matching expressions to handle different cases.