Previous Up Next
B.2 Labeled arguments


In the core language, as in most languages, arguments are anonymous.

Labeled arguments are a convenient extension to the core language that allow to consistently label arguments in the declaration of functions and in their application. Labeled arguments increase safety, since argument labels are checked against their definitions. Moreover, labeled arguments also increase flexibility since they can be passed in a different order than the one of their definition. Finally, labeled arguments can be used solely for documentation purposes.

For instance, the erroneous exchange of two arguments of the same type ---an error the typechecker would not catch--- can be avoided by labeling the arguments with distinct labels. As an example, the module StdLabels.String provides a function sub with the following type:
      
StdLabels.String.sub;;
- : string -> pos:int -> len:int -> string = <fun>
This function expects three arguments: the first one is anonymous, the second and third ones are labeled pos and len, respectively. A call to this function can be written
      
String.sub "Hello" ~pos:0 ~len:4
or equivalently,
      
String.sub "Hello" ~len:4 ~pos:0
since labeled arguments can be passed to the function in a different order. Labels are (lexically) enclosed between ~ and :, so as to distinguish them from variables.

By default, standard library functions are not labeled. The module StdLabels redefines some modules of the standard library with labeled versions of some functions. Thus, one can include the command
      
open StdLabels;;
at the beginning of a file to benefit from labeled versions of the libraries. Then, String.sub could have been used as a short hand for StdLabels.String.sub in the example above.

Labeled arguments of a function are declared by labeling the arguments accordingly in the function declaration. For example, the labeled version of substring could have been defined as
      
let substring s ~pos:x ~length:y = String.sub s x y;;
Additionally, there is a possible short-cut that allows us to use the name of the label for the name of the variable. Then, both the ending : mark at the end of the label and the variable are omitted. Hence, the following definition of substring is equivalent to the previous one.
      
let substring s ~pos ~length = String.sub s pos length;;


Previous Up Next