In Ocaml, is there a simple construct/style to extend a defined type?
Say, if we have the boolean type
bool2 = True | False
Now we want to extend it for 3-valued logic. In Ocaml, is there more elegant one than redefining bool2 like this:
bool3 = True | False | ThirdOne
Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).
The * symbol is used to separate elements of a tuple in data type definitions.
Polymorphic variants provide this functionality:
type bool2 = [ `True | `False ]
type bool3 = [ bool2 | `Third_one ]
That's it.
There is another useful shortcut for polymorphic variants. In pattern-matching, use the type name preceded by #
:
let is_bool2 = function
#bool2 -> true
| `Third_one -> false
Polymorphic variants should be used with caution as they can easily lead to confusing error messages. If the original type bool2
is not a polymorphic variant anyway, the union of two types is achieved as follows. Let's assume bool2
is the core type bool
, our definition using classic variants is:
type bool3 = Bool of bool | Third_one
In pattern-matching, the compiler will check that all cases are covered, without requiring type annotations. It looks like this:
match x with | Bool true -> ... | Bool false -> ... | Third_one -> ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With