OCaml: A list that can contain two types?
2 answers
One option is polymorphic options . You can determine the type of the list using:
# type mylist = [`I of int | `S of string] list ;;
type mylist = [ `I of int | `S of string ] list
Then define values ββlike:
# let r : mylist = [`I 10; `S "hello"; `I 0; `S "world"] ;;
val r : mylist = [`I 10; `S "hello"; `I 0; `S "world"]
However, you must be careful to add type annotations, since polymorphic variants are "public" types. For example, the following legal:
# let s = [`I 0; `S "foo"; `B true]
val s : [> `B of bool | `I of int | `S of string ] list =
[`I 0; `S "foo"; `B true]
To exclude a list type from non-integer or string values, use the annotation:
# let s : mylist = [`I 0; `S "foo"; `B true];;
This expression has type [> `B of bool ] but is here used with type
[ `I of int | `S of string ]
The second variant type does not allow tag(s) `B
+7
source to share