288 Chapter 6 Data Types
Accessing the value of a union is done with a pattern-matching structure.
Pattern matching in F# is specified with the match reserved word. The general
form of the construct is as follows:
match pattern with
| expression_list 1 - > expression 1
|...
| expression_listn-> expressionn
The pattern can be any data type. The expression list can include wild card
characters ( _ ) or be solely a wild card character. For example, consider the
following match construct:
let a = 7;;
let b = "grape";;
let x = match (a, b) with
| 4, "apple" -> apple
| _, "grape" -> grape
| _ -> fruit;;
To display the type of the intReal union, the following function could
be used:
let printType value =
match value with
| IntValue value -> printfn "It is an integer"
| RealValue value -> printfn "It is a float";;
The following lines show calls to this function and the output:
printType ir1;;
It is an integer
printType ir2;;
It is a float
6.10.5 Evaluation
Unions are potentially unsafe constructs in some languages. They are
one of the reasons why C and C++ are not strongly typed: These languages
do not allow type checking of references to their unions. On the other
hand, unions can be safely used, as in their design in Ada, ML, Haskell,
and F#.
Neither Java nor C# includes unions, which may be reflective of the growing
concern for safety in some programming languages.