1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="hevea 1.08">
<LINK rel="stylesheet" type="text/css" href="manual.css">
<TITLE>
Labels and variants
</TITLE>
</HEAD>
<BODY >
<A HREF="manual005.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<A HREF="manual007.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<HR>
<H1 CLASS="chapter"><A NAME="htoc36">Chapter 4</A> Labels and variants</H1> <A NAME="c:labl-examples"></A>
<I>(Chapter written by Jacques Garrigue)</I><BR>
<BR>
<BR>
<BR>
<BR>
<BR>
This chapter gives an overview of the new features in
Objective Caml 3: labels, and polymorphic variants.<BR>
<BR>
<H2 CLASS="section"><A NAME="htoc37">4.1</A> Labels</H2>
If you have a look at modules ending in <TT>Labels</TT> in the standard
library, you will see that function types have annotations you did not
have in the functions you defined yourself.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>ListLabels.map;;
</FONT><FONT COLOR=maroon>- : f:('a -> 'b) -> 'a list -> 'b list = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>StringLabels.sub;;
</FONT>- : string -> pos:int -> len:int -> string = <fun>
</FONT></PRE>
Such annotations of the form <TT>name:</TT> are called <EM>labels</EM>. 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 <TT>~</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f ~x ~y = x - y;;
</FONT><FONT COLOR=maroon>val f : x:int -> y:int -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let x = 3 and y = 2 in f ~x ~y;;
</FONT>- : int = 1
</FONT></PRE>
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
<TT>~name:</TT>. This also applies when the argument is not a variable.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f ~x:x1 ~y:y1 = x1 - y1;;
</FONT><FONT COLOR=maroon>val f : x:int -> y:int -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>f ~x:3 ~y:2;;
</FONT>- : int = 1
</FONT></PRE>
Labels obey the same rules as other identifiers in Caml, that is you
cannot use a reserved keyword (like <TT>in</TT> or <TT>to</TT>) as label.<BR>
<BR>
Formal parameters and arguments are matched according to their
respective labels<SUP><A NAME="text1" HREF="#note1">1</A></SUP>, 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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f ~x ~y = x - y;;
</FONT><FONT COLOR=maroon>val f : x:int -> y:int -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>f ~y:2 ~x:3;;
</FONT>- : int = 1
<FONT COLOR=black>#</FONT><FONT COLOR=blue>ListLabels.fold_left;;
</FONT>- : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>ListLabels.fold_left [1;2;3] ~init:0 ~f:(+);;
</FONT>- : int = 6
<FONT COLOR=black>#</FONT><FONT COLOR=blue>ListLabels.fold_left ~init:0;;
</FONT>- : f:(int -> 'a -> int) -> 'a list -> int = <fun>
</FONT></PRE>
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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let hline ~x:x1 ~x:x2 ~y = (x1, x2, y);;
</FONT><FONT COLOR=maroon>val hline : x:'a -> x:'b -> y:'c -> 'a * 'b * 'c = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>hline ~x:3 ~y:2 ~x:5;;
</FONT>- : int * int * int = (3, 5, 2)
</FONT></PRE>
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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>f 3 2;;
</FONT><FONT COLOR=maroon>- : int = 1
<FONT COLOR=black>#</FONT><FONT COLOR=blue>ListLabels.map succ [1;2;3];;
</FONT>- : int list = [2; 3; 4]
</FONT></PRE>
But beware that functions like <TT>ListLabels.fold_left</TT> whose result
type is a type variable will never be considered as totally applied.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>ListLabels.fold_left <U>(+)</U> 0 [1;2;3];;
</FONT><FONT COLOR=maroon>This expression has type int -> int -> int but is here used with type 'a list
</FONT></PRE>
When 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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let h g = g ~x:3 ~y:2;;
</FONT><FONT COLOR=maroon>val h : (x:int -> y:int -> 'a) -> 'a = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>h f;;
</FONT>- : int = 1
<FONT COLOR=black>#</FONT><FONT COLOR=blue>h <U>(+)</U>;;
</FONT>This expression has type int -> int -> int but is here used with type
x:int -> y:int -> 'a
</FONT></PRE>
<H3 CLASS="subsection"><A NAME="htoc38">4.1.1</A> Optional arguments</H3>
An interesting feature of labeled arguments is that they can be made
optional. For optional parameters, the question mark <TT>?</TT> replaces the
tilde <TT>~</TT> of non-optional ones, and the label is also prefixed by <TT>?</TT>
in the function type.
Default values may be given for such optional parameters.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let bump ?(step = 1) x = x + step;;
</FONT><FONT COLOR=maroon>val bump : ?step:int -> int -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>bump 2;;
</FONT>- : int = 3
<FONT COLOR=black>#</FONT><FONT COLOR=blue>bump ~step:3 2;;
</FONT>- : int = 5
</FONT></PRE>
A 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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);;
</FONT><FONT COLOR=maroon>val test : ?x:int -> ?y:int -> unit -> ?z:int -> unit -> int * int * int =
<fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>test ();;
</FONT>- : ?z:int -> unit -> int * int * int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>test ~x:2 () ~z:3 ();;
</FONT>- : int * int * int = (2, 0, 3)
</FONT></PRE>
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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>test ~y:2 ~x:3 () ();;
</FONT><FONT COLOR=maroon>- : int * int * int = (3, 2, 0)
<FONT COLOR=black>#</FONT><FONT COLOR=blue>test () () ~z:1 ~y:2 ~x:3;;
</FONT>- : int * int * int = (3, 2, 1)
<FONT COLOR=black>#</FONT><FONT COLOR=blue><U>(test () ())</U> ~z:1;;
</FONT>This expression is not a function, it cannot be applied
</FONT></PRE>
Here <TT>(test () ())</TT> is already <TT>(0,0,0)</TT> and cannot be further
applied.<BR>
<BR>
Optional arguments are actually implemented as option types. If
you do not give a default value, you have access to their internal
representation, <TT>type 'a option = None | Some of 'a</TT>. You can then
provide different behaviors when an argument is present or not.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let bump ?step x =
match step with
| None -> x * 2
| Some y -> x + y
;;
</FONT><FONT COLOR=maroon>val bump : ?step:int -> int -> int = <fun>
</FONT></PRE>
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 <TT>?</TT>. This question mark disables the wrapping of optional
argument in an option type.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let test2 ?x ?y () = test ?x ?y () ();;
</FONT><FONT COLOR=maroon>val test2 : ?x:int -> ?y:int -> unit -> int * int * int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>test2 ?x:None;;
</FONT>- : ?y:int -> unit -> int * int * int = <fun>
</FONT></PRE>
<H3 CLASS="subsection"><A NAME="htoc39">4.1.2</A> Labels and type inference</H3>
<A NAME="ss:label-inference"></A>
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.<BR>
<BR>
You can see it in the following two examples.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let h' g = g ~y:2 ~x:3;;
</FONT><FONT COLOR=maroon>val h' : (y:int -> x:int -> 'a) -> 'a = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>h' <U>f</U>;;
</FONT>This expression has type x:int -> y:int -> int but is here used with type
y:int -> x:int -> 'a
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let bump_it bump x =
bump ~step:2 x;;
</FONT>val bump_it : (step:int -> 'a -> 'b) -> 'a -> 'b = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>bump_it <U>bump</U> 1;;
</FONT>This expression has type ?step:int -> int -> int but is here used with type
step:int -> 'a -> 'b
</FONT></PRE>
The first case is simple: <TT>g</TT> is passed <TT>~y</TT> and then <TT>~x</TT>, but <TT>f</TT>
expects <TT>~x</TT> and then <TT>~y</TT>. This is correctly handled if we know the
type of <TT>g</TT> to be <TT>x:int -> y:int -> int</TT> in advance, but otherwise
this causes the above type clash. The simplest workaround is to apply
formal parameters in a standard order.<BR>
<BR>
The second example is more subtle: while we intended the argument
<TT>bump</TT> to be of type <TT>?step:int -> int -> int</TT>, it is inferred as
<TT>step:int -> int -> 'a</TT>.
These two types being incompatible (internally normal and optional
arguments are different), a type error occurs when applying <TT>bump_it</TT>
to the real <TT>bump</TT>.<BR>
<BR>
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 <TT>g</TT> or <TT>bump</TT>. 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.<BR>
<BR>
The right way to solve this problem for optional parameters is to add
a type annotation to the argument <TT>bump</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let bump_it (bump : ?step:int -> int -> int) x =
bump ~step:2 x;;
</FONT><FONT COLOR=maroon>val bump_it : (?step:int -> int -> int) -> int -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>bump_it bump 1;;
</FONT>- : int = 3
</FONT></PRE>
In 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.<BR>
<BR>
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 <TT>None</TT> for all optional
parameters.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let twice f (x : int) = f(f x);;
</FONT><FONT COLOR=maroon>val twice : (int -> int) -> int -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>twice bump 2;;
</FONT>- : int = 8
</FONT></PRE>
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.<BR>
<BR>
<H3 CLASS="subsection"><A NAME="htoc40">4.1.3</A> Suggestions for labeling</H3>
Like for names, choosing labels for functions is not an easy task. A
good labeling is a labeling which
<UL CLASS="itemize"><LI CLASS="li-itemize">
makes programs more readable,
<LI CLASS="li-itemize">is easy to remember,
<LI CLASS="li-itemize">when possible, allows useful partial applications.
</UL>
We explain here the rules we applied when labeling Objective Caml
libraries.<BR>
<BR>
To speak in an “object-oriented” way, one can consider that each
function has a main argument, its <EM>object</EM>, and other arguments
related with its action, the <EM>parameters</EM>. To permit the
combination of functions through functionals in commuting label mode, the
object will not be labeled. Its role is clear by the function
itself. The parameters are labeled with names reminding either of
their nature or role. Best labels combine in their meaning nature and
role. When this is not possible the role is to prefer, since the nature will
often be given by the type itself. Obscure abbreviations should be
avoided.
<PRE><FONT COLOR=maroon>ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list
UnixLabels.write : file_descr -> buf:string -> pos:int -> len:int -> unit
</FONT></PRE>
When there are several objects of same nature and role, they are all
left unlabeled.
<PRE><FONT COLOR=maroon>ListLabels.iter2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> unit
</FONT></PRE>
When there is no preferable object, all arguments are labeled.
<PRE><FONT COLOR=maroon>StringLabels.blit :
src:string -> src_pos:int -> dst:string -> dst_pos:int -> len:int -> unit
</FONT></PRE>
However, when there is only one argument, it is often left unlabeled.
<PRE><FONT COLOR=maroon>StringLabels.create : int -> string
</FONT></PRE>
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 <TT>ListLabels.fold_left</TT>.<BR>
<BR>
Here are some of the label names you will find throughout the
libraries.<BR>
<BR>
<DIV CLASS="center"><TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1 WIDTH="80%">
<TR><TD ALIGN=center NOWRAP><B>Label</B></TD>
<TD ALIGN=center NOWRAP><B>Meaning</B></TD>
</TR>
<TR><TD ALIGN=left NOWRAP>
<TT>f:</TT></TD>
<TD ALIGN=left NOWRAP>a function to be applied</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>pos:</TT></TD>
<TD ALIGN=left NOWRAP>a position in a string or array</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>len:</TT></TD>
<TD ALIGN=left NOWRAP>a length</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>buf:</TT></TD>
<TD ALIGN=left NOWRAP>a string used as buffer</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>src:</TT></TD>
<TD ALIGN=left NOWRAP>the source of an operation</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>dst:</TT></TD>
<TD ALIGN=left NOWRAP>the destination of an operation</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>init:</TT></TD>
<TD ALIGN=left NOWRAP>the initial value for an iterator</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>cmp:</TT></TD>
<TD ALIGN=left NOWRAP>a comparison function, <I>e.g.</I> <TT>Pervasives.compare</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>mode:</TT></TD>
<TD ALIGN=left NOWRAP>an operation mode or a flag list</TD>
</TR></TABLE></DIV><BR>
<BR>
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.<BR>
<BR>
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 <TT>ocaml</TT> toplevel, the documentation
is only used when a more detailed specification is needed.<BR>
<BR>
<H2 CLASS="section"><A NAME="htoc41">4.2</A> Polymorphic variants</H2>
Variants as presented in section <A HREF="manual003.html#s:tut-recvariants">1.4</A> are a
powerful tool to build data structures and algorithms. However they
sometimes lack flexibility when used in modular programming. This is
due to the fact every constructor reserves a name to be used with a
unique type. One cannot use the same name in another type, or consider
a value of some type to belong to some other type with more
constructors.<BR>
<BR>
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.<BR>
<BR>
<H3 CLASS="subsection">Basic use</H3>
In programs, polymorphic variants work like usual ones. You just have
to prefix their names with a backquote character <TT>`</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>[`On; `Off];;
</FONT><FONT COLOR=maroon>- : [> `Off | `On ] list = [`On; `Off]
<FONT COLOR=black>#</FONT><FONT COLOR=blue>`Number 1;;
</FONT>- : [> `Number of int ] = `Number 1
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let f = function `On -> 1 | `Off -> 0 | `Number n -> n;;
</FONT>val f : [< `Number of int | `Off | `On ] -> int = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>List.map f [`On; `Off];;
</FONT>- : int list = [1; 0]
</FONT></PRE>
<TT>[>`Off|`On] list</TT> means that to match this list, you should at
least be able to match <TT>`Off</TT> and <TT>`On</TT>, without argument.
<TT>[<`On|`Off|`Number of int]</TT> means that <TT>f</TT> may be applied to <TT>`Off</TT>,
<TT>`On</TT> (both without argument), or <TT>`Number</TT> <I>n</I> where
<I>n</I> is an integer.
The <TT>></TT> and <TT><</TT> inside the variant type shows that they may still be
refined, either by defining more tags or allowing less. As such they
contain an implicit type variable. Both variant types appearing only
once in the type, the implicit type variables they constrain are not
shown.<BR>
<BR>
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 <TT><</TT> or
<TT>></TT>, but just an enumeration of the tags and their associated types,
just like in a normal datatype definition.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];;
</FONT><FONT COLOR=maroon>type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let rec map f : 'a vlist -> 'b vlist = function
| `Nil -> `Nil
| `Cons(a, l) -> `Cons(f a, map f l)
;;
</FONT>val map : ('a -> 'b) -> 'a vlist -> 'b vlist = <fun>
</FONT></PRE>
<H3 CLASS="subsection">Advanced use</H3>
Type-checking polymorphic variants is a subtle thing, and some
expressions may result in more complex type information.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f = function `A -> `C | `B -> `D | x -> x;;
</FONT><FONT COLOR=maroon>val f : ([> `A | `B | `C | `D ] as 'a) -> 'a = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>f `E;;
</FONT>- : [> `A | `B | `C | `D | `E ] = `E
</FONT></PRE>
Here we are seeing two phenomena. First, since this matching is open
(the last case catches any tag), we obtain the type <TT>[> `A | `B]</TT>
rather than <TT>[< `A | `B]</TT> in a closed matching. Then, since <TT>x</TT> is
returned as is, input and return types are identical. The notation <TT>as 'a</TT> denotes such type sharing. If we apply <TT>f</TT> to yet another tag
<TT>`E</TT>, it gets added to the list.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f1 = function `A x -> x = 1 | `B -> true | `C -> false
let f2 = function `A x -> x = "a" | `B -> true ;;
</FONT><FONT COLOR=maroon>val f1 : [< `A of int | `B | `C ] -> bool = <fun>
val f2 : [< `A of string | `B ] -> bool = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let f x = f1 x && f2 x;;
</FONT>val f : [< `A of string & int | `B ] -> bool = <fun>
</FONT></PRE>
Here <TT>f1</TT> and <TT>f2</TT> both accept the variant tags <TT>`A</TT> and <TT>`B</TT>, but the
argument of <TT>`A</TT> is <TT>int</TT> for <TT>f1</TT> and <TT>string</TT> for <TT>f2</TT>. In <TT>f</TT>'s
type <TT>`C</TT>, only accepted by <TT>f1</TT>, disappears, but both argument types
appear for <TT>`A</TT> as <TT>int & string</TT>. This means that if we
pass the variant tag <TT>`A</TT> to <TT>f</TT>, its argument should be <EM>both</EM>
<TT>int</TT> and <TT>string</TT>. Since there is no such value, <TT>f</TT> cannot be
applied to <TT>`A</TT>, and <TT>`B</TT> is the only accepted input.<BR>
<BR>
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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];;
</FONT><FONT COLOR=maroon>type 'a wlist = [ `Cons of 'a * 'a wlist | `Nil | `Snoc of 'a wlist * 'a ]
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);;
</FONT>val wlist_of_vlist : 'a vlist -> 'a wlist = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let open_vlist l = (l : 'a vlist :> [> 'a vlist]);;
</FONT>val open_vlist : 'a vlist -> [> 'a vlist ] = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>fun x -> (x :> [`A|`B|`C]);;
</FONT>- : [< `A | `B | `C ] -> [ `A | `B | `C ] = <fun>
</FONT></PRE>
You may also selectively coerce values through pattern matching.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let split_cases = function
| `Nil | `Cons _ as x -> `A x
| `Snoc _ as x -> `B x
;;
</FONT><FONT COLOR=maroon>val split_cases :
[< `Cons of 'a | `Nil | `Snoc of 'b ] ->
[> `A of [> `Cons of 'a | `Nil ] | `B of [> `Snoc of 'b ] ] = <fun>
</FONT></PRE>
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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let num x = `Num x
let eval1 eval (`Num x) = x
let rec eval x = eval1 eval x ;;
</FONT><FONT COLOR=maroon>val num : 'a -> [> `Num of 'a ] = <fun>
val eval1 : 'a -> [< `Num of 'b ] -> 'b = <fun>
val eval : [< `Num of 'a ] -> 'a = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>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 ;;
</FONT>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>
</FONT></PRE>
To make this even more confortable, you may use type definitions as
abbreviations for or-patterns. That is, if you have defined <TT>type myvariant = [`Tag1 int | `Tag2 bool]</TT>, then the pattern <TT>#myvariant</TT> is
equivalent to writing <TT>(`Tag1(_ : int) | `Tag2(_ : bool))</TT>.<BR>
<BR>
Such abbreviations may be used alone,
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f = function
| #myvariant -> "myvariant"
| `Tag3 -> "Tag3";;
</FONT><FONT COLOR=maroon>val f : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>
</FONT></PRE>
or combined with with aliases.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";;
</FONT><FONT COLOR=maroon>val g1 : [< `Tag1 of 'a | `Tag2 of 'b ] -> string = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let g = function
| #myvariant as x -> g1 x
| `Tag3 -> "Tag3";;
</FONT>val g : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>
</FONT></PRE>
<H3 CLASS="subsection"><A NAME="htoc42">4.2.1</A> Weaknesses of polymorphic variants</H3>
After seeing the power of polymorphic variants, one may wonder why
they were added to core language variants, rather than replacing them.<BR>
<BR>
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.<BR>
<BR>
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.<BR>
<BR>
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.<BR>
<BR>
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.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>type abc = [`A | `B | `C] ;;
</FONT><FONT COLOR=maroon>type abc = [ `A | `B | `C ]
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let f = function
| `As -> "A"
| #abc -> "other" ;;
</FONT>val f : [< `A | `As | `B | `C ] -> string = <fun>
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let f : abc -> string = f ;;
</FONT>val f : abc -> string = <fun>
</FONT></PRE>
You can avoid such risks by annotating the definition itself.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let f : abc -> string = function
| <U>`As</U> -> "A"
| #abc -> "other" ;;
</FONT><FONT COLOR=maroon>Warning U: this match case is unused.
val f : abc -> string = <fun>
</FONT></PRE>
<HR WIDTH="50%" SIZE=1><DL CLASS="list"><DT CLASS="dt-list"><FONT SIZE=5><A NAME="note1" HREF="#text1">1</A></FONT><DD CLASS="dd-list">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 (<TT>-nolabels</TT>
options) is now deprecated for normal use.
</DL>
<HR>
<A HREF="manual005.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<A HREF="manual007.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>
|