A discriminated union in OCaml is like a C union combined with an enum. So your example of a number
type could be represented like this in C:
enum number_tag {
ZERO, INTEGER, REAL
};
union number_value {
int i; /* Only access this if tag is INTEGER */
float f; /* Only access this if tag is REAL */
};
struct number {
enum number_tag tag;
union number_value value;
};
So you can ask what a number's type is by accessing the enum and then access the appropriate field of the union based on the value of the enum. Of course C won't stop from accessing the wrong field of the union.
OCaml on the other hand eliminates the possibility of accessing the wrong field. Since you can only access the values by pattern matching, you know that you always have the right type.
Pattern matching on a value of the number
type would look like this in OCaml:
match value_of_type_number with
| Zero ->
(* Handle the case that the number is Zero *)
| Integer i ->
(* Handle the case that the number is an Integer with the value i *)
| Float f ->
(* Handle the case that the number is a Float with the value f *)
The equivalent of that would be this:
switch(value_of_type_number.tag) {
case ZERO:
/* Handle the case that the number is Zero */
break;
case INTEGER:
int i = value_of_type_number.value.i;
/* Handle the case that the number is an Integer with the value i */
break;
case FLOAT:
float f = value_of_type_number.value.f;
/* Handle the case that the number is a Float with the value f */
break;
}
Is type 'a set
a union definition? How about type 'a set = 'a list
? and why?
type 'a set
is not a definition at all. It just specifies the interface. It says that an implementation of this interface must define a type named set
which takes one type parameter.
type 'a set = 'a list
is a definition, but not of a discriminated union. It's simply a type alias. That is it says "'a set
is just another name for 'a list
'. A definition of a discriminated union would have a constructor as the first thing after the equals sign. Constructors always start with capital letters.