OCaml: elenco che potrebbe contenere due tipi?
Domanda
Invece di specificare un elenco int o un elenco di stringhe, posso specificare un elenco i cui membri devono essere stringhe o ints, ma nient'altro?
Soluzione
Potresti fare:
type element = IntElement of int | StringElement of string;;
e quindi utilizza un elenco di elemento
s.
Altri suggerimenti
Un'opzione è varianti polimorfiche . Puoi definire il tipo di elenco usando:
# type mylist = [`I of int | `S of string] list ;;
type mylist = [ `I of int | `S of string ] list
Quindi definire valori come:
# let r : mylist = [`I 10; `S "hello"; `I 0; `S "world"] ;;
val r : mylist = [`I 10; `S "hello"; `I 0; `S "world"]
Devi fare attenzione ad aggiungere annotazioni di tipo, però, perché le varianti polimorfiche sono " open " tipi. Ad esempio, è legale quanto segue:
# 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]
Per evitare che il tipo di un elenco consenta valori non interi o stringa, utilizzare un'annotazione:
# 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow