This chapter gives an overview of the new features in Objective Caml 3: labels, and polymorphic variants.

#ListLabels.map;; - : f:('a -> 'b) -> 'a list -> 'b list = <fun> #StringLabels.sub;; - : string -> pos:int -> len:int -> string = <fun>Such annotations of the form

#let f ~x ~y = x - y;; val f : x:int -> y:int -> int = <fun> #let x = 3 and y = 2 in f ~x ~y;; - : int = 1When you want to use distinct names for the variable and the label appearing in the type, you can use a naming label of the form

#let f ~x:x1 ~y:y1 = x1 - y1;; val f : x:int -> y:int -> int = <fun> #f ~x:3 ~y:2;; - : int = 1Labels obey the same rules as other identifiers in Caml, that is you cannot use a reserved keyword (like

Formal parameters and arguments are matched according to their respective labels

#let f ~x ~y = x - y;; val f : x:int -> y:int -> int = <fun> #f ~y:2 ~x:3;; - : int = 1 #ListLabels.fold_left;; - : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun> #ListLabels.fold_left [1;2;3] ~init:0 ~f:(+);; - : int = 6 #ListLabels.fold_left ~init:0;; - : f:(int -> 'a -> int) -> 'a list -> int = <fun>If in a function several arguments bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.

#let hline ~x:x1 ~x:x2 ~y = (x1, x2, y);; val hline : x:'a -> x:'b -> y:'c -> 'a * 'b * 'c = <fun> #hline ~x:3 ~y:2 ~x:5;; - : int * int * int = (3, 5, 2)As an exception to the above parameter matching rules, if an application is total, labels may be omitted. In practice, most applications are total, so that labels can be omitted in applications.

#f 3 2;; - : int = 1 #ListLabels.map succ [1;2;3];; - : int list = [2; 3; 4]But beware that functions like

#ListLabels.fold_leftWhen a function is passed as an argument to an higher-order function, labels must match in both types. Neither adding nor removing labels are allowed.(+)0 [1;2;3];; This expression has type int -> int -> int but is here used with type 'a list

#let h g = g ~x:3 ~y:2;; val h : (x:int -> y:int -> 'a) -> 'a = <fun> #h f;; - : int = 1 #h(+);; This expression has type int -> int -> int but is here used with type x:int -> y:int -> 'a

#let bump ?(step = 1) x = x + step;; val bump : ?step:int -> int -> int = <fun> #bump 2;; - : int = 3 #bump ~step:3 2;; - : int = 5A function taking some optional arguments must also take at least one non-labeled argument. This is because the criterion for deciding whether an optional has been omitted is the application on a non-labeled argument appearing after this optional argument in the function type.

#let test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);; val test : ?x:int -> ?y:int -> unit -> ?z:int -> unit -> int * int * int = <fun> #test ();; - : ?z:int -> unit -> int * int * int = <fun> #test ~x:2 () ~z:3 ();; - : int * int * int = (2, 0, 3)Optional parameters may also commute with non-optional or unlabelled ones, as long as they are applied simultaneously. By nature, optional arguments do not commute with unlabeled arguments applied independently.

#test ~y:2 ~x:3 () ();; - : int * int * int = (3, 2, 0) #test () () ~z:1 ~y:2 ~x:3;; - : int * int * int = (3, 2, 1) #Here(test () ())~z:1;; This expression is not a function, it cannot be applied

Optional arguments are actually implemented as option types. If you do not give a default value, you have access to their internal representation,

#let bump ?step x = match step with | None -> x * 2 | Some y -> x + y ;; val bump : ?step:int -> int -> int = <fun>It may also be useful to relay an optional argument from a function call to another. This can be done by prefixing the applied argument with

#let test2 ?x ?y () = test ?x ?y () ();; val test2 : ?x:int -> ?y:int -> unit -> int * int * int = <fun> #test2 ?x:None;; - : ?y:int -> unit -> int * int * int = <fun>

You can see it in the following two examples.

#let h' g = g ~y:2 ~x:3;; val h' : (y:int -> x:int -> 'a) -> 'a = <fun> #h'The first case is simple:f;; This expression has type x:int -> y:int -> int but is here used with type y:int -> x:int -> 'a #let bump_it bump x = bump ~step:2 x;; val bump_it : (step:int -> 'a -> 'b) -> 'a -> 'b = <fun> #bump_itbump1;; This expression has type ?step:int -> int -> int but is here used with type step:int -> 'a -> 'b

The second example is more subtle: while we intended the argument

We will not try here to explain in detail how type inference works. One must just understand that there is not enough information in the above program to deduce the correct type of

The right way to solve this problem for optional parameters is to add a type annotation to the argument

#let bump_it (bump : ?step:int -> int -> int) x = bump ~step:2 x;; val bump_it : (?step:int -> int -> int) -> int -> int = <fun> #bump_it bump 1;; - : int = 3In practive, such problems appear mostly when using objects whose methods have optional arguments, so that writing the type of object arguments is often a good idea.

Normally the compiler generates a type error if you attempt to pass to a function a parameter whose type is different from the expected one. However, in the specific case where the expected type is a non-labeled function type, and the argument is a function expecting optional parameters, the compiler will attempt to transform the argument to have it match the expected type, by passing

#let twice f (x : int) = f(f x);; val twice : (int -> int) -> int -> int = <fun> #twice bump 2;; - : int = 8This transformation is coherent with the intended semantics, including side-effects. That is, if the application of optional parameters shall produce side-effects, these are delayed until the received function is really applied to an argument.

- makes programs more readable,
- is easy to remember,
- when possible, allows useful partial applications.

To speak in an “object-oriented” way, one can consider that each function has a main argument, its

ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list UnixLabels.write : file_descr -> buf:string -> pos:int -> len:int -> unitWhen there are several objects of same nature and role, they are all left unlabeled.

ListLabels.iter2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> unitWhen there is no preferable object, all arguments are labeled.

StringLabels.blit : src:string -> src_pos:int -> dst:string -> dst_pos:int -> len:int -> unitHowever, when there is only one argument, it is often left unlabeled.

StringLabels.create : int -> stringThis principle also applies to functions of several arguments whose return type is a type variable, as long as the role of each argument is not ambiguous. Labeling such functions may lead to awkward error messages when one attempts to omit labels in an application, as we have seen with

Here are some of the label names you will find throughout the libraries.

Label |
Meaning |

f: |
a function to be applied |

pos: |
a position in a string or array |

len: |
a length |

buf: |
a string used as buffer |

src: |
the source of an operation |

dst: |
the destination of an operation |

init: |
the initial value for an iterator |

cmp: |
a comparison function, e.g. Pervasives.compare |

mode: |
an operation mode or a flag list |

All these are only suggestions, but one shall keep in mind that the choice of labels is essential for readability. Bizarre choices will make the program harder to maintain.

In the ideal, the right function name with right labels shall be enough to understand the function's meaning. Since one can get this information with OCamlBrowser or the

With polymorphic variants, this original assumption is removed. That is, a variant tag does not belong to any type in particular, the type system will just check that it is an admissible value according to its use. You need not define a type before using a variant tag. A variant type will be inferred independently for each of its uses.

#[`On; `Off];; - : [> `Off | `On ] list = [`On; `Off] #`Number 1;; - : [> `Number of int ] = `Number 1 #let f = function `On -> 1 | `Off -> 0 | `Number n -> n;; val f : [< `Number of int | `Off | `On ] -> int = <fun> #List.map f [`On; `Off];; - : int list = [1; 0]

The above variant types were polymorphic, allowing further refinement. When writing type annotations, one will most often describe fixed variant types, that is types that can be no longer refined. This is also the case for type abbreviations. Such types do not contain

#type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];; type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ] #let rec map f : 'a vlist -> 'b vlist = function | `Nil -> `Nil | `Cons(a, l) -> `Cons(f a, map f l) ;; val map : ('a -> 'b) -> 'a vlist -> 'b vlist = <fun>

#let f = function `A -> `C | `B -> `D | x -> x;; val f : ([> `A | `B | `C | `D ] as 'a) -> 'a = <fun> #f `E;; - : [> `A | `B | `C | `D | `E ] = `EHere we are seeing two phenomena. First, since this matching is open (the last case catches any tag), we obtain the type

#let f1 = function `A x -> x = 1 | `B -> true | `C -> false let f2 = function `A x -> x = "a" | `B -> true ;; val f1 : [< `A of int | `B | `C ] -> bool = <fun> val f2 : [< `A of string | `B ] -> bool = <fun> #let f x = f1 x && f2 x;; val f : [< `A of string & int | `B ] -> bool = <fun>Here

Even if a value has a fixed variant type, one can still give it a larger type through coercions. Coercions are normally written with both the source type and the destination type, but in simple cases the source type may be omitted.

#type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];; type 'a wlist = [ `Cons of 'a * 'a wlist | `Nil | `Snoc of 'a wlist * 'a ] #let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);; val wlist_of_vlist : 'a vlist -> 'a wlist = <fun> #let open_vlist l = (l : 'a vlist :> [> 'a vlist]);; val open_vlist : 'a vlist -> [> 'a vlist ] = <fun> #fun x -> (x :> [`A|`B|`C]);; - : [< `A | `B | `C ] -> [ `A | `B | `C ] = <fun>You may also selectively coerce values through pattern matching.

#let split_cases = function | `Nil | `Cons _ as x -> `A x | `Snoc _ as x -> `B x ;; val split_cases : [< `Cons of 'a | `Nil | `Snoc of 'b ] -> [> `A of [> `Cons of 'a | `Nil ] | `B of [> `Snoc of 'b ] ] = <fun>When an or-pattern composed of variant tags is wrapped inside an alias-pattern, the alias is given a type containing only the tags enumerated in the or-pattern. This allows for many useful idioms, like incremental definition of functions.

#let num x = `Num x let eval1 eval (`Num x) = x let rec eval x = eval1 eval x ;; val num : 'a -> [> `Num of 'a ] = <fun> val eval1 : 'a -> [< `Num of 'b ] -> 'b = <fun> val eval : [< `Num of 'a ] -> 'a = <fun> #let plus x y = `Plus(x,y) let eval2 eval = function | `Plus(x,y) -> eval x + eval y | `Num _ as x -> eval1 eval x let rec eval x = eval2 eval x ;; val plus : 'a -> 'b -> [> `Plus of 'a * 'b ] = <fun> val eval2 : ('a -> int) -> [< `Num of int | `Plus of 'a * 'a ] -> int = <fun> val eval : ([< `Num of int | `Plus of 'a * 'a ] as 'a) -> int = <fun>To make this even more confortable, you may use type definitions as abbreviations for or-patterns. That is, if you have defined

Such abbreviations may be used alone,

#let f = function | #myvariant -> "myvariant" | `Tag3 -> "Tag3";; val f : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>or combined with with aliases.

#let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";; val g1 : [< `Tag1 of 'a | `Tag2 of 'b ] -> string = <fun> #let g = function | #myvariant as x -> g1 x | `Tag3 -> "Tag3";; val g : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>

The answer is two fold. One first aspect is that while being pretty efficient, the lack of static type information allows for less optimizations, and makes polymorphic variants slightly heavier than core language ones. However noticeable differences would only appear on huge data structures.

More important is the fact that polymorphic variants, while being type-safe, result in a weaker type discipline. That is, core language variants do actually much more than ensuring type-safety, they also check that you use only declared constructors, that all constructors present in a data-structure are compatible, and they enforce typing constraints to their parameters.

For this reason, you must be more careful about making types explicit when you use polymorphic variants. When you write a library, this is easy since you can describe exact types in interfaces, but for simple programs you are probably better off with core language variants.

Beware also that certain idioms make trivial errors very hard to find. For instance, the following code is probably wrong but the compiler has no way to see it.

#type abc = [`A | `B | `C] ;; type abc = [ `A | `B | `C ] #let f = function | `As -> "A" | #abc -> "other" ;; val f : [< `A | `As | `B | `C ] -> string = <fun> #let f : abc -> string = f ;; val f : abc -> string = <fun>You can avoid such risks by annotating the definition itself.

#let f : abc -> string = function |`As-> "A" | #abc -> "other" ;; Warning U: this match case is unused. val f : abc -> string = <fun>

- 1
- This correspond to the commuting label mode
of Objective Caml 3.00 through 3.02, with some additional flexibility
on total applications. The so-called classic mode (
`-nolabels`options) is now deprecated for normal use.