Tuesday, February 1, 2011

Studying F# : Discriminated Union

The enum of C# works as halfway between C++'s one and Java's one.

C++
enum Suit {CLUB, DIAMOND, HEART, SPADE};
The type of the enum is just int, and this is not type-safe.

Java (since JavaSE 5)
public enum Suit {
    CLUB, DIAMOND, HEART, SPADE;
}
The type of the enum is Suit, and this is type-safe.

C#
enum Suit {CLUB, DIAMOND, HEART, SPADE};
The type of the enum is Suit, but it can cast for int easily, so this is halfway type-safe.

In F#

We, of course, are able to use C#'s enum in F# because both these are on CLR. But, there is another kind of enum in F#. It is the "Discriminated Union". This paradigm is rather similar to Java's enum.

Discriminated Union in F#
type Suit =
    | Club
    | Diamond
    | Heart
    | Spade
The type of the enum is Suit, and this is type-safe.

No comments:

Post a Comment