简体   繁体   中英

What does a square bracketed type signate: `[< t ]` mean in OCaml?

I have been playing around with Dream and Caqti in OCaml and I recently ran into a type signature I've never seen before:

  val handle_error : [< Caqti_error.t ] -> Dream.response t

  let handle_error e =
    print_endline (Caqti_error.show e); error_template |> Dream.html

What does the [< ] around the type Caqti_error.t mean? At first I thought it was some sort of weird Monadic or Wrapper type, but I'm not sure what it is, what it does, or why.

This is a polymorphic variant type, see https://ocaml.org/manual/polyvariant.html for more details.

In brief, polymorphic variants are a structural version of ordinary variants. And a type like [< `A | `B] [< `A | `B] in

let f: [< `A | `B ] -> int = function
| `A -> 0
| `B -> 1

means that the function accepts at most the constructor `A or `B as an argument. Moreover, since polymorphic variants are structural, one does not need to define the constructor `A or `B before starting to use them.

Moreover, the caqti library is using an inline type abbreviation to avoid repeating the set of allowed variants multiple time. A good example of such use case would be

type t = [ `A | `B ]
let switch : [< t ] -> [> t ] = function
| `A -> `B
| `B -> `A

In the example above, the type [> t] means that both `A and `B were explicitly presents, but more variants might be added later. For instance, the type of list l

let l = [ switch `B; `C ]

is [> t | `C ] [> t | `C ] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM