Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse and extend the defined type in Ocaml

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
like image 443
zell Avatar asked Jul 30 '11 06:07

zell


People also ask

What does :: do in OCaml?

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] ).

What does asterisk mean in OCaml?

The * symbol is used to separate elements of a tuple in data type definitions.


1 Answers

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 -> ...
like image 145
Martin Jambon Avatar answered Oct 15 '22 22:10

Martin Jambon