OCaml:可能包含两种类型的列表?

时间:2009-09-15 18:00:52

标签: list types ocaml

我可以指定一个列表,其成员必须是字符串或整数,而不是指定一个int列表或字符串列表,而不是其他内容吗?

2 个答案:

答案 0 :(得分:8)

你可以这样做:

type element = IntElement of int | StringElement of string;;

然后使用element s。

列表

答案 1 :(得分:7)

一个选项是polymorphic variants。您可以使用以下方法定义列表类型:

# type mylist = [`I of int | `S of string] list ;;
type mylist = [ `I of int | `S of string ] list

然后定义诸如以下的值:

# let r : mylist = [`I 10; `S "hello"; `I 0; `S "world"] ;;
val r : mylist = [`I 10; `S "hello"; `I 0; `S "world"]

但是,您必须小心添加类型注释,因为多态变体是“开放”类型。例如,以下是合法的:

# 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]

要防止列表类型允许非整数或字符串值,请使用注释:

# 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