Дизъюнктное объединение в OCaml похоже на союз C, объединенный с enum. Так ваш пример число
тип мог быть представлен как это в 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;
};
Таким образом, можно спросить, что тип числа, получая доступ к enum, и затем получите доступ к соответствующей области союза на основе ценности enum. Конечно, C не будет мешать получить доступ к неправильной области союза.
OCaml, с другой стороны, устраняет возможность доступа к неправильной области. Так как можно только получить доступ к ценностям сопоставлением с образцом, вы знаете, что у вас всегда есть правильный тип.
Сопоставление с образцом на ценности число
тип было бы похоже на это в 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 *)
Эквивалент этого был бы этим:
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;
}
<Кодируют> тип 'набор определение союза? Как насчет печатают 'набор = 'список
? и почему?
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.