2

int リストまたは文字列リストを指定する代わりに、メンバーが文字列または int である必要があるリストを指定できますか?

4

2 に答える 2

8

あなたがすることができます:

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

s のリストを使用しますelement

于 2009-09-15T18:07:09.530 に答える
7

1つのオプションは多形バリアントです。リストのタイプは、次を使用して定義できます。

# 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 に答える