質問
intリストまたは文字列リストを指定する代わりに、メンバーが文字列またはintでなければならないリストを指定できますか?
解決
できること:
type element = IntElement of int | StringElement of string;;
その後、 element
sのリストを使用します。
他のヒント
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
所属していません StackOverflow