If you have a look at modules ending in Labels in the standard library, you will see that function types have annotations you did not have in the functions you defined yourself.

# ListLabels.map;;

- : f:('a -> 'b) -> 'a list -> 'b list = <fun>

# StringLabels.sub;;

- : string -> pos:int -> len:int -> string = <fun>

Such annotations of the form name: are called *labels*. They are
meant to document the code, allow more checking, and give more
flexibility to function application.
You can give such names to arguments in your programs, by prefixing them
with a tilde ~.

# 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 = 1

When 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 ~name:. This also applies when the argument is not a variable.

# let f ~x:x1 ~y:y1 = x1 - y1;;

val f : x:int -> y:int -> int = <fun>

# f ~x:3 ~y:2;;

- : int = 1

Labels obey the same rules as other identifiers in OCaml, that is you cannot use a reserved keyword (like in or to) as a label.

Formal parameters and arguments are matched according to their respective labels, the absence of label being interpreted as the empty label. This allows commuting arguments in applications. One can also partially apply a function on any argument, creating a new function of the remaining parameters.

# 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 several arguments of a function 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)

An interesting feature of labeled arguments is that they can be made optional. For optional parameters, the question mark ? replaces the tilde ~ of non-optional ones, and the label is also prefixed by ? in the function type. Default values may be given for such optional parameters.

# let bump ?(step = 1) x = x + step;;

val bump : ?step:int -> int -> int = <fun>

# bump 2;;

- : int = 3

# bump ~step:3 2;;

- : int = 5

A function taking some optional arguments must also take at least one non-optional argument. The criterion for deciding whether an optional argument has been omitted is the non-labeled application of an argument appearing after this optional argument in the function type. Note that if that argument is labeled, you will only be able to eliminate optional arguments by totally applying the function, omitting all optional arguments and omitting all labels for all remaining arguments.

# 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 unlabeled 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)

# (test () ()) ~z:1 ;;

Error: This expression has type int * int * int
This is not a function; it cannot be applied.

Here (test () ()) is already (0,0,0) and cannot be further applied.

Optional arguments are actually implemented as option types. If you do not give a default value, you have access to their internal representation, type 'a option = None | Some of 'a. You can then provide different behaviors when an argument is present or not.

# 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 ?. This question mark disables the wrapping of optional argument in an option type.

# 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>

While they provide an increased comfort for writing function applications, labels and optional arguments have the pitfall that they cannot be inferred as completely as the rest of the language.

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' f ;;

Error: This expression has type x:int -> y:int -> int
but an expression was expected of 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_it bump 1 ;;

Error: This expression has type ?step:int -> int -> int
but an expression was expected of type step:int -> 'a -> 'b

The first case is simple: g is passed ~y and then ~x, but f expects ~x and then ~y. This is correctly handled if we know the type of g to be x:int -> y:int -> int in advance, but otherwise this causes the above type clash. The simplest workaround is to apply formal parameters in a standard order.

The second example is more subtle: while we intended the argument bump to be of type ?step:int -> int -> int, it is inferred as step:int -> int -> 'a. These two types being incompatible (internally normal and optional arguments are different), a type error occurs when applying bump_it to the real bump.

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 g or bump. That is, there is no way to know whether an argument is optional or not, or which is the correct order, by looking only at how a function is applied. The strategy used by the compiler is to assume that there are no optional arguments, and that applications are done in the right order.

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

# 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 = 3

In practice, such problems appear mostly when using objects whose methods have optional arguments, so 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 None for all optional parameters.

# let twice f (x : int) = f(f x);;

val twice : (int -> int) -> int -> int = <fun>

# twice bump 2;;

- : int = 8

This 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.

Like for names, choosing labels for functions is not an easy task. A good labeling is one which

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

We explain here the rules we applied when labeling OCaml libraries.

To speak in an “object-oriented” way, one can consider that each
function has a main argument, its *object*, and other arguments
related with its action, the *parameters*. To permit the
combination of functions through functionals in commuting label mode, the
object will not be labeled. Its role is clear from the function
itself. The parameters are labeled with names reminding of
their nature or their role. The best labels combine nature and
role. When this is not possible the role is to be preferred, since the
nature will
often be given by the type itself. Obscure abbreviations should be
avoided.

```
ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list
UnixLabels.write : file_descr -> buf:bytes -> pos:int -> len:int -> unit
```

When there are several objects of same nature and role, they are all left unlabeled.

```
ListLabels.iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
```

When there is no preferable object, all arguments are labeled.

BytesLabels.blit : src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit

However, when there is only one argument, it is often left unlabeled.

BytesLabels.create : int -> bytes

This 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 ListLabels.fold_left.

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, array or byte sequence |

len: | a length |

buf: | a byte sequence or 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. Stdlib.compare |

mode: | an operation mode or a flag list |

All these are only suggestions, but 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 should be enough to understand the function’s meaning. Since one can get this information with OCamlBrowser or the ocaml toplevel, the documentation is only used when a more detailed specification is needed.

Copyright © 2022 Institut National de
Recherche en Informatique et en Automatique