You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo


We have covered discriminated unions, which are helpful for defining types of things within a set. However, each discriminated union case is a distinctly different class and is too heavyweight a construct in some situations. Many times you simply want to define a group of related constant integral values, and in those situations, you can use enumerations.

An enumeration is a primitive integral type, such as int or sbyte, which also contains a series of named constant values. An enumeration is just a wrapper over that integral type, however, so an instance of an enumerated type can have a value not defined within that enumeration.

Creating Enumerations

To create an enumeration, you use the same syntax as for creating discriminated unions, but each data tag must be given a constant value of the same type. Example 6-6 shows creating an enumeration type for chess pieces. Each enumeration field value must be unique. In the example, the field values correspond to the chess pieces’ material value.

Example 6-6. Declaring an enumeration

type ChessPiece =
    | Empty  = 0
    | Pawn   = 1
    | Knight = 3
    | Bishop = 4
    | Rook   = 5
    | Queen  = 8
    | King   = 1000000

To use an enumeration value, simply use the fully qualified field name. Example 6-7 initializes an 8×8 array to represent locations on a chessboard.

With our ChessPiece enum as is, it would be impossible to differentiate between a black piece and a white piece. However, because each ChessPiece value is simply an integer, we can get sneaky and treat ...

The best content for your career. Discover unlimited learning on demand for around $1/day.