2

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

4

2 回答 2

8

你可以这样做:

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

然后使用elements 的列表。

于 2009-09-15T18:07:09.530 回答
7

一种选择是多态变体。您可以使用以下方式定义列表的类型:

# 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
于 2009-09-15T19:17:29.967 回答