OCaml: A list that can contain two types?

Instead of specifying a list of int or a list of strings, can I specify a list whose members should be either strings or targets, but no more?

+2


source to share


2 answers


You can do:

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

      



and then use the list element

s.

+8


source


One option is polymorphic options . You can determine 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 ​​like:

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

      



However, you must be careful to add type annotations, since polymorphic variants are "public" types. For example, the following 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 exclude a list type from non-integer or string values, use the 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

      

+7


source







All Articles