简体   繁体   中英

OCaml: List that could contain two types?

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

You could do:

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

and then use a list of element s.

One option is polymorphic variants . You can define the type of the list using:

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

Then define values such as:

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

You have to be careful to add type annotations, though, because polymorphic variants are "open" types. Eg, the following is legal:

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

To prevent the type of a list from allowing non-integer-or-string values, use an annotation:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM