Search code examples
ocamlellipsis

ocaml type definition contains ellipsis


I'm reading some Ocaml project's source code and I'm new to Ocaml.I'm confused in the following code,which is a some kind of type definition in a .ml file.

type event = Event.t = ..

What's the meaning of '..' in the code,I searched the manual but get nothing. And in the event.mli,the type definition is :

type t = ..
type event = t = ..

Any help is appreciated,thanks.


Solution

  • Its new "extensible variant types". See http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec251 for details.

    You can declare a empty extensible variant type with

    type t = ..
    

    then later you can add new constructors like

    type t += Foo | Bar of int
    

    You can add constructors to extensible variants more than once places of programs. Instead, you cannot enjoy non-exhaustiveness check at pattern match, which is available for normal variants.

    type event = t = .. declares an alias event of already existing extensible type t. = .. is required to make the new type also extensible.

    type event = t = ..
    type event += Poo  (* you cannot do this if type event = t *)
    

    Note

    Extensible variant types may be useful when:

    • You do not want to fix the set of the constructors.
    • You feel constructors are rather loosely related each other and see no benefit to declare them in one place.

    For example, the type of various errors of an application is a good candidate to define as an EVT: an app may fail due to a network issue, an auth failure, disk full and so on. They are unrelated with each other and come from many parts of the app. In that case you may want to define the type error as an EVT:

    (* module Error *)
    type t = ..
    
    (* module Web *)
    type Error.t += Http of int (* ex. 404 *)
    
    (* module Tempfile *)
    type Error.t += Diskfull of Path.t
    
    (* module ErrorHandler *)
    let print_error (e : Error.t) = match e with
      | Web.HTTP stat -> ...
      | Tempfile.Diskfull path -> ...
      | ...
    

    You may notice it looks like exceptions, actually EVT is generalized version of exception.