Of course, both is possible in OCaml.
If you want to make it possible for an expression, to evaluate to a value of two (or more different types), then it means, that you want to create a new type that will include all these types. Recall, that a type can be compared with a set. So, if you want to define a new type t
, that can contain values of type t1
and t2
, then you need to have a union. Since types t1
and t2
have different properties, it is natural, that we would like to have an ability to distinguish them later, so we would like to make the union discriminated. It happens, that OCaml has a built-in support for discriminated unions - variants, e.g.,
type t = T1 of t1 | T2 of t2
This type definition creates a new type, that is a discriminated union of types t1
and t2
. The definition naturally creates projection and injection function. To inject a value x
of type t1
into type t
, use T1 x
(correspondingly for a value x
of type t2
, use T2 x
). Use pattern match to project a value y
from type t
to either t1
or t2
, e.g., match y with T1 -> ... | T2 -> ...
.