你可以这样做:
type element = IntElement of int | StringElement of string;;
Run Code Online (Sandbox Code Playgroud)
然后使用elements 列表.
一种选择是多态变体.您可以使用以下方法定义列表的类型:
# type mylist = [`I of int | `S of string] list ;;
type mylist = [ `I of int | `S of string ] list
Run Code Online (Sandbox Code Playgroud)
然后定义值,例如:
# let r : mylist = [`I 10; `S "hello"; `I 0; `S "world"] ;;
val r : mylist = [`I 10; `S "hello"; `I 0; `S "world"]
Run Code Online (Sandbox Code Playgroud)
但是,您必须小心添加类型注释,因为多态变体是"开放"类型.例如,以下是合法的:
# 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]
Run Code Online (Sandbox Code Playgroud)
要防止列表类型允许非整数或字符串值,请使用注释:
# 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
Run Code Online (Sandbox Code Playgroud)