OCaml: ¿Lista que podría contener dos tipos?
Pregunta
En lugar de especificar una lista int o una lista de cadenas, ¿podría especificar una lista cuyos miembros deben ser cadenas o entradas, pero nada más?
Solución
Podrías hacer:
type element = IntElement of int | StringElement of string;;
y luego use una lista de elementos
s.
Otros consejos
Una opción es variantes polimórficas . Puede definir el tipo de lista usando:
# type mylist = [`I of int | `S of string] list ;;
type mylist = [ `I of int | `S of string ] list
Luego defina valores como:
# let r : mylist = [`I 10; `S "hello"; `I 0; `S "world"] ;;
val r : mylist = [`I 10; `S "hello"; `I 0; `S "world"]
Sin embargo, debe tener cuidado al agregar anotaciones de tipo, porque las variantes polimórficas están "abiertas". tipos. Por ejemplo, lo siguiente es 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]
Para evitar que el tipo de una lista permita valores no enteros o de cadena, use una anotación:
# 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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow