File: lablexamples.html

package info (click to toggle)
ocaml-doc 4.11-2
  • links: PTS, VCS
  • area: non-free
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 20,580 kB
  • sloc: sh: 37; makefile: 11
file content (1022 lines) | stat: -rw-r--r-- 41,379 bytes parent folder | download
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
<!DOCTYPE html>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="generator" content="hevea 2.32">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="manual.css">
<title>Chapter 4  Labels and variants</title>
</head>
<body>
<a href="objectexamples.html"><img src="previous_motif.svg" alt="Previous"></a>
<a href="index.html"><img src="contents_motif.svg" alt="Up"></a>
<a href="polymorphism.html"><img src="next_motif.svg" alt="Next"></a>
<hr>
<h1 class="chapter" id="sec44">Chapter 4  Labels and variants</h1>
<ul>
<li><a href="lablexamples.html#s%3Alabels">4.1  Labels</a>
</li><li><a href="lablexamples.html#s%3Apolymorphic-variants">4.2  Polymorphic variants</a>
</li></ul>
<p> <a id="c:labl-examples"></a>
</p><p>
<span class="c009">(Chapter written by Jacques Garrigue)</span></p><p><br>
<br>
</p><p>This chapter gives an overview of the new features in
OCaml 3: labels, and polymorphic variants.</p>
<h2 class="section" id="s:labels"><a class="section-anchor" href="#s:labels" aria-hidden="true"></a>4.1  Labels</h2>
<p>If you have a look at modules ending in <span class="c003">Labels</span> in the standard
library, you will see that function types have annotations you did not
have in the functions you defined yourself.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> ListLabels.map;;</div>



<div class="pre caml-output ok">- : f:('a -&gt; 'b) -&gt; 'a list -&gt; 'b list = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> StringLabels.sub;;</div>



<div class="pre caml-output ok">- : string -&gt; pos:int -&gt; len:int -&gt; string = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>Such annotations of the form <span class="c003">name:</span> 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 <span class="c003">~</span>.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f ~x ~y = x - y;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : x:int -&gt; y:int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> x = 3 <span class="ocamlkeyword">and</span> y = 2 <span class="ocamlkeyword">in</span> f ~x ~y;;</div>



<div class="pre caml-output ok">- : int = 1</div></div>

</div><p>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
<span class="c003">~name:</span>. This also applies when the argument is not a variable.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f ~x:x1 ~y:y1 = x1 - y1;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : x:int -&gt; y:int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> f ~x:3 ~y:2;;</div>



<div class="pre caml-output ok">- : int = 1</div></div>

</div><p>Labels obey the same rules as other identifiers in OCaml, that is you
cannot use a reserved keyword (like <span class="c003">in</span> or <span class="c003">to</span>) as label.</p><p>Formal parameters and arguments are matched according to their
respective labels<sup><a id="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.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f ~x ~y = x - y;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : x:int -&gt; y:int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> f ~y:2 ~x:3;;</div>



<div class="pre caml-output ok">- : int = 1</div></div>
<div class="ocaml">



<div class="pre caml-input"> ListLabels.fold_left;;</div>



<div class="pre caml-output ok">- : f:('a -&gt; 'b -&gt; 'a) -&gt; init:'a -&gt; 'b list -&gt; 'a = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> ListLabels.fold_left [1;2;3] ~init:0 ~f:( + );;</div>



<div class="pre caml-output ok">- : int = 6</div></div>
<div class="ocaml">



<div class="pre caml-input"> ListLabels.fold_left ~init:0;;</div>



<div class="pre caml-output ok">- : f:(int -&gt; 'a -&gt; int) -&gt; 'a list -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>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.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> hline ~x:x1 ~x:x2 ~y = (x1, x2, y);;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> hline : x:'a -&gt; x:'b -&gt; y:'c -&gt; 'a * 'b * 'c = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> hline ~x:3 ~y:2 ~x:5;;</div>



<div class="pre caml-output ok">- : int * int * int = (3, 5, 2)</div></div>

</div><p>As an exception to the above parameter matching rules, if an
application is total (omitting all optional arguments), labels may be
omitted.
In practice, many applications are total, so that labels can often be
omitted.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> f 3 2;;</div>



<div class="pre caml-output ok">- : int = 1</div></div>
<div class="ocaml">



<div class="pre caml-input"> ListLabels.map succ [1;2;3];;</div>



<div class="pre caml-output ok">- : int list = [2; 3; 4]</div></div>

</div><p>


But beware that functions like <span class="c003">ListLabels.fold_left</span> whose result
type is a type variable will never be considered as totally applied.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> ListLabels.fold_left <span class="ocamlhighlight">( + )</span> 0 [1;2;3];;</div>



<div class="pre caml-output error"><span class="ocamlerror">Error</span>: This expression has type int -&gt; int -&gt; int
       but an expression was expected of type 'a list</div></div>

</div><p>When a function is passed as an argument to a higher-order function,
labels must match in both types. Neither adding nor removing labels
are allowed.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> h g = g ~x:3 ~y:2;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> h : (x:int -&gt; y:int -&gt; 'a) -&gt; 'a = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> h f;;</div>



<div class="pre caml-output ok">- : int = 1</div></div>
<div class="ocaml">



<div class="pre caml-input"> h <span class="ocamlhighlight">( + )</span> ;;</div>



<div class="pre caml-output error"><span class="ocamlerror">Error</span>: This expression has type int -&gt; int -&gt; int
       but an expression was expected of type x:int -&gt; y:int -&gt; 'a</div></div>

</div><p>


Note that when you don’t need an argument, you can still use a wildcard
pattern, but you must prefix it with the label.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> h (<span class="ocamlkeyword">fun</span> ~x:_ ~y -&gt; y+1);;</div>



<div class="pre caml-output ok">- : int = 3</div></div>

</div>
<h3 class="subsection" id="ss:optional-arguments"><a class="section-anchor" href="#ss:optional-arguments" aria-hidden="true"></a>4.1.1  Optional arguments</h3>
<p>An interesting feature of labeled arguments is that they can be made
optional. For optional parameters, the question mark <span class="c003">?</span> replaces the
tilde <span class="c003">~</span> of non-optional ones, and the label is also prefixed by <span class="c003">?</span>
in the function type.
Default values may be given for such optional parameters.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> bump ?(step = 1) x = x + step;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> bump : ?step:int -&gt; int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> bump 2;;</div>



<div class="pre caml-output ok">- : int = 3</div></div>
<div class="ocaml">



<div class="pre caml-input"> bump ~step:3 2;;</div>



<div class="pre caml-output ok">- : int = 5</div></div>

</div><p>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.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> test : ?x:int -&gt; ?y:int -&gt; unit -&gt; ?z:int -&gt; unit -&gt; int * int * int =
  &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> test ();;</div>



<div class="pre caml-output ok">- : ?z:int -&gt; unit -&gt; int * int * int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> test ~x:2 () ~z:3 ();;</div>



<div class="pre caml-output ok">- : int * int * int = (2, 0, 3)</div></div>

</div><p>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.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> test ~y:2 ~x:3 () ();;</div>



<div class="pre caml-output ok">- : int * int * int = (3, 2, 0)</div></div>
<div class="ocaml">



<div class="pre caml-input"> test () () ~z:1 ~y:2 ~x:3;;</div>



<div class="pre caml-output ok">- : int * int * int = (3, 2, 1)</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlhighlight">(test () ())</span> ~z:1 ;;</div>



<div class="pre caml-output error"><span class="ocamlerror">Error</span>: This expression has type int * int * int
       This is not a function; it cannot be applied.</div></div>

</div><p>


Here <span class="c003">(test () ())</span> is already <span class="c003">(0,0,0)</span> and cannot be further
applied.</p><p>Optional arguments are actually implemented as option types. If
you do not give a default value, you have access to their internal
representation, <span class="c003">type 'a option = None | Some of 'a</span>. You can then
provide different behaviors when an argument is present or not.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> bump ?step x =
   <span class="ocamlkeyword">match</span> step <span class="ocamlkeyword">with</span>
   | None -&gt; x * 2
   | Some y -&gt; x + y
 ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> bump : ?step:int -&gt; int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>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 <span class="c003">?</span>. This question mark disables the wrapping of optional
argument in an option type.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> test2 ?x ?y () = test ?x ?y () ();;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> test2 : ?x:int -&gt; ?y:int -&gt; unit -&gt; int * int * int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> test2 ?x:None;;</div>



<div class="pre caml-output ok">- : ?y:int -&gt; unit -&gt; int * int * int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div>
<h3 class="subsection" id="ss:label-inference"><a class="section-anchor" href="#ss:label-inference" aria-hidden="true"></a>4.1.2  Labels and type inference</h3>
<p>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.</p><p>You can see it in the following two examples.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> h' g = g ~y:2 ~x:3;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> h' : (y:int -&gt; x:int -&gt; 'a) -&gt; 'a = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> h' <span class="ocamlhighlight">f</span> ;;</div>



<div class="pre caml-output error"><span class="ocamlerror">Error</span>: This expression has type x:int -&gt; y:int -&gt; int
       but an expression was expected of type y:int -&gt; x:int -&gt; 'a</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> bump_it bump x =
   bump ~step:2 x;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> bump_it : (step:int -&gt; 'a -&gt; 'b) -&gt; 'a -&gt; 'b = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> bump_it <span class="ocamlhighlight">bump</span> 1 ;;</div>



<div class="pre caml-output error"><span class="ocamlerror">Error</span>: This expression has type ?step:int -&gt; int -&gt; int
       but an expression was expected of type step:int -&gt; 'a -&gt; 'b</div></div>

</div><p>


The first case is simple: <span class="c003">g</span> is passed <span class="c003">~y</span> and then <span class="c003">~x</span>, but <span class="c003">f</span>
expects <span class="c003">~x</span> and then <span class="c003">~y</span>. This is correctly handled if we know the
type of <span class="c003">g</span> to be <span class="c003">x:int -&gt; y:int -&gt; int</span> in advance, but otherwise
this causes the above type clash. The simplest workaround is to apply
formal parameters in a standard order.</p><p>The second example is more subtle: while we intended the argument
<span class="c003">bump</span> to be of type <span class="c003">?step:int -&gt; int -&gt; int</span>, it is inferred as
<span class="c003">step:int -&gt; int -&gt; 'a</span>.
These two types being incompatible (internally normal and optional
arguments are different), a type error occurs when applying <span class="c003">bump_it</span>
to the real <span class="c003">bump</span>.</p><p>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 <span class="c003">g</span> or <span class="c003">bump</span>. 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.</p><p>The right way to solve this problem for optional parameters is to add
a type annotation to the argument <span class="c003">bump</span>.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> bump_it (bump : ?step:int -&gt; int -&gt; int) x =
   bump ~step:2 x;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> bump_it : (?step:int -&gt; int -&gt; int) -&gt; int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> bump_it bump 1;;</div>



<div class="pre caml-output ok">- : int = 3</div></div>

</div><p>


In practice, 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.</p><p>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 <span class="c003">None</span> for all optional
parameters.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> twice f (x : int) = f(f x);;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> twice : (int -&gt; int) -&gt; int -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> twice bump 2;;</div>



<div class="pre caml-output ok">- : int = 8</div></div>

</div><p>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.</p>
<h3 class="subsection" id="ss:label-suggestions"><a class="section-anchor" href="#ss:label-suggestions" aria-hidden="true"></a>4.1.3  Suggestions for labeling</h3>
<p>Like for names, choosing labels for functions is not an easy task. A
good labeling is a labeling which</p><ul class="itemize"><li class="li-itemize">
makes programs more readable,
</li><li class="li-itemize">is easy to remember,
</li><li class="li-itemize">when possible, allows useful partial applications.
</li></ul><p>We explain here the rules we applied when labeling OCaml
libraries.</p><p>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 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.
</p><pre>
<span class="c003">ListLabels.map : f:('a -&gt; 'b) -&gt; 'a list -&gt; 'b list</span>
UnixLabels.write : file_descr -&gt; buf:bytes -&gt; pos:int -&gt; len:int -&gt; unit
</pre><p>When there are several objects of same nature and role, they are all
left unlabeled.
</p><pre>
<span class="c003">ListLabels.iter2 : f:('a -&gt; 'b -&gt; 'c) -&gt; 'a list -&gt; 'b list -&gt; unit</span>
</pre><p>When there is no preferable object, all arguments are labeled.
</p><pre>
BytesLabels.blit :
  src:bytes -&gt; src_pos:int -&gt; dst:bytes -&gt; dst_pos:int -&gt; len:int -&gt; unit
</pre><p>However, when there is only one argument, it is often left unlabeled.
</p><pre>
BytesLabels.create : int -&gt; bytes
</pre><p>
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 <span class="c003">ListLabels.fold_left</span>.</p><p>Here are some of the label names you will find throughout the
libraries.</p><div class="tableau">
<div class="center"><table class="c000 cellpadding1" border=1><tr><td class="c014"><span class="c013">Label</span></td><td class="c014"><span class="c013">Meaning</span> </td></tr>
<tr><td class="c016">
<span class="c003">f:</span></td><td class="c016">a function to be applied </td></tr>
<tr><td class="c016"><span class="c003">pos:</span></td><td class="c016">a position in a string, array or byte sequence </td></tr>
<tr><td class="c016"><span class="c003">len:</span></td><td class="c016">a length </td></tr>
<tr><td class="c016"><span class="c003">buf:</span></td><td class="c016">a byte sequence or string used as buffer </td></tr>
<tr><td class="c016"><span class="c003">src:</span></td><td class="c016">the source of an operation </td></tr>
<tr><td class="c016"><span class="c003">dst:</span></td><td class="c016">the destination of an operation </td></tr>
<tr><td class="c016"><span class="c003">init:</span></td><td class="c016">the initial value for an iterator </td></tr>
<tr><td class="c016"><span class="c003">cmp:</span></td><td class="c016">a comparison function, <span class="c009">e.g.</span> <span class="c003">Stdlib.compare</span> </td></tr>
<tr><td class="c016"><span class="c003">mode:</span></td><td class="c016">an operation mode or a flag list </td></tr>
</table></div></div><p>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.</p><p>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 <span class="c003">ocaml</span> toplevel, the documentation
is only used when a more detailed specification is needed.</p>
<h2 class="section" id="s:polymorphic-variants"><a class="section-anchor" href="#s:polymorphic-variants" aria-hidden="true"></a>4.2  Polymorphic variants</h2>
<p>Variants as presented in section <a href="coreexamples.html#s%3Atut-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 that every constructor is assigned to a unique type
when defined and used. Even if the same name appears in the definition
of multiple types, the constructor itself belongs to only one type.
Therefore, one cannot decide that a given constructor belongs to
multiple types, or consider a value of some type to belong to some
other type with more constructors.</p><p>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.</p><h3 class="subsection" id="ss:polyvariant:basic-use"><a class="section-anchor" href="#ss:polyvariant:basic-use" aria-hidden="true"></a>Basic use</h3>
<p>In programs, polymorphic variants work like usual ones. You just have
to prefix their names with a backquote character <span class="c003">`</span>.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> [`On; `Off];;</div>



<div class="pre caml-output ok">- : [&gt; `Off | `On ] list = [`On; `Off]</div></div>
<div class="ocaml">



<div class="pre caml-input"> `Number 1;;</div>



<div class="pre caml-output ok">- : [&gt; `Number <span class="ocamlkeyword">of</span> int ] = `Number 1</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f = <span class="ocamlkeyword">function</span> `On -&gt; 1 | `Off -&gt; 0 | `Number n -&gt; n;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : [&lt; `Number <span class="ocamlkeyword">of</span> int | `Off | `On ] -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> List.map f [`On; `Off];;</div>



<div class="pre caml-output ok">- : int list = [1; 0]</div></div>

</div><p>


<span class="c003">[&gt;`Off|`On] list</span> means that to match this list, you should at
least be able to match <span class="c003">`Off</span> and <span class="c003">`On</span>, without argument.
<span class="c003">[&lt;`On|`Off|`Number of int]</span> means that <span class="c003">f</span> may be applied to <span class="c003">`Off</span>,
<span class="c003">`On</span> (both without argument), or <span class="c003">`Number</span> <span class="c009">n</span> where
<span class="c009">n</span> is an integer.
The <span class="c003">&gt;</span> and <span class="c003">&lt;</span> inside the variant types show that they may still be
refined, either by defining more tags or by allowing less. As such, they
contain an implicit type variable. Because each of the variant types
appears only once in the whole type, their implicit type variables are
not shown.</p><p>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 cannot be refined. This is
also the case for type abbreviations. Such types do not contain <span class="c003">&lt;</span> or
<span class="c003">&gt;</span>, but just an enumeration of the tags and their associated types,
just like in a normal datatype definition.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">type</span> 'a vlist = [`Nil | `Cons <span class="ocamlkeyword">of</span> 'a * 'a vlist];;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">type</span> 'a vlist = [ `Cons <span class="ocamlkeyword">of</span> 'a * 'a vlist | `Nil ]</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> <span class="ocamlkeyword">rec</span> map f : 'a vlist -&gt; 'b vlist = <span class="ocamlkeyword">function</span>
   | `Nil -&gt; `Nil
   | `Cons(a, l) -&gt; `Cons(f a, map f l)
 ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> map : ('a -&gt; 'b) -&gt; 'a vlist -&gt; 'b vlist = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><h3 class="subsection" id="ss:polyvariant-advanced"><a class="section-anchor" href="#ss:polyvariant-advanced" aria-hidden="true"></a>Advanced use</h3>
<p>Type-checking polymorphic variants is a subtle thing, and some
expressions may result in more complex type information.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f = <span class="ocamlkeyword">function</span> `A -&gt; `C | `B -&gt; `D | x -&gt; x;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : ([&gt; `A | `B | `C | `D ] <span class="ocamlkeyword">as</span> 'a) -&gt; 'a = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> f `E;;</div>



<div class="pre caml-output ok">- : [&gt; `A | `B | `C | `D | `E ] = `E</div></div>

</div><p>


Here we are seeing two phenomena. First, since this matching is open
(the last case catches any tag), we obtain the type <span class="c003">[&gt; `A | `B]</span>
rather than <span class="c003">[&lt; `A | `B]</span> in a closed matching. Then, since <span class="c003">x</span> is
returned as is, input and return types are identical. The notation <span class="c003">as 'a</span> denotes such type sharing. If we apply <span class="c003">f</span> to yet another tag
<span class="c003">`E</span>, it gets added to the list.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f1 = <span class="ocamlkeyword">function</span> `A x -&gt; x = 1 | `B -&gt; <span class="ocamlkeyword">true</span> | `C -&gt; <span class="ocamlkeyword">false</span>
 <span class="ocamlkeyword">let</span> f2 = <span class="ocamlkeyword">function</span> `A x -&gt; x = <span class="ocamlstring">"a"</span> | `B -&gt; <span class="ocamlkeyword">true</span> ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f1 : [&lt; `A <span class="ocamlkeyword">of</span> int | `B | `C ] -&gt; bool = &lt;<span class="ocamlkeyword">fun</span>&gt;
<span class="ocamlkeyword">val</span> f2 : [&lt; `A <span class="ocamlkeyword">of</span> string | `B ] -&gt; bool = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f x = f1 x &amp;&amp; f2 x;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : [&lt; `A <span class="ocamlkeyword">of</span> string &amp; int | `B ] -&gt; bool = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>


Here <span class="c003">f1</span> and <span class="c003">f2</span> both accept the variant tags <span class="c003">`A</span> and <span class="c003">`B</span>, but the
argument of <span class="c003">`A</span> is <span class="c003">int</span> for <span class="c003">f1</span> and <span class="c003">string</span> for <span class="c003">f2</span>. In <span class="c003">f</span>’s
type <span class="c003">`C</span>, only accepted by <span class="c003">f1</span>, disappears, but both argument types
appear for <span class="c003">`A</span> as <span class="c003">int &amp; string</span>. This means that if we
pass the variant tag <span class="c003">`A</span> to <span class="c003">f</span>, its argument should be <em>both</em>
<span class="c003">int</span> and <span class="c003">string</span>. Since there is no such value, <span class="c003">f</span> cannot be
applied to <span class="c003">`A</span>, and <span class="c003">`B</span> is the only accepted input.</p><p>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.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">type</span> 'a wlist = [`Nil | `Cons <span class="ocamlkeyword">of</span> 'a * 'a wlist | `Snoc <span class="ocamlkeyword">of</span> 'a wlist * 'a];;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">type</span> 'a wlist = [ `Cons <span class="ocamlkeyword">of</span> 'a * 'a wlist | `Nil | `Snoc <span class="ocamlkeyword">of</span> 'a wlist * 'a ]</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> wlist_of_vlist  l = (l : 'a vlist :&gt; 'a wlist);;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> wlist_of_vlist : 'a vlist -&gt; 'a wlist = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> open_vlist l = (l : 'a vlist :&gt; [&gt; 'a vlist]);;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> open_vlist : 'a vlist -&gt; [&gt; 'a vlist ] = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">fun</span> x -&gt; (x :&gt; [`A|`B|`C]);;</div>



<div class="pre caml-output ok">- : [&lt; `A | `B | `C ] -&gt; [ `A | `B | `C ] = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>You may also selectively coerce values through pattern matching.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> split_cases = <span class="ocamlkeyword">function</span>
   | `Nil | `Cons _ <span class="ocamlkeyword">as</span> x -&gt; `A x
   | `Snoc _ <span class="ocamlkeyword">as</span> x -&gt; `B x
 ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> split_cases :
  [&lt; `Cons <span class="ocamlkeyword">of</span> 'a | `Nil | `Snoc <span class="ocamlkeyword">of</span> 'b ] -&gt;
  [&gt; `A <span class="ocamlkeyword">of</span> [&gt; `Cons <span class="ocamlkeyword">of</span> 'a | `Nil ] | `B <span class="ocamlkeyword">of</span> [&gt; `Snoc <span class="ocamlkeyword">of</span> 'b ] ] = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>


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.</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> num x = `Num x
 <span class="ocamlkeyword">let</span> eval1 eval (`Num x) = x
 <span class="ocamlkeyword">let</span> <span class="ocamlkeyword">rec</span> eval x = eval1 eval x ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> num : 'a -&gt; [&gt; `Num <span class="ocamlkeyword">of</span> 'a ] = &lt;<span class="ocamlkeyword">fun</span>&gt;
<span class="ocamlkeyword">val</span> eval1 : 'a -&gt; [&lt; `Num <span class="ocamlkeyword">of</span> 'b ] -&gt; 'b = &lt;<span class="ocamlkeyword">fun</span>&gt;
<span class="ocamlkeyword">val</span> eval : [&lt; `Num <span class="ocamlkeyword">of</span> 'a ] -&gt; 'a = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> plus x y = `Plus(x,y)
 <span class="ocamlkeyword">let</span> eval2 eval = <span class="ocamlkeyword">function</span>
   | `Plus(x,y) -&gt; eval x + eval y
   | `Num _ <span class="ocamlkeyword">as</span> x -&gt; eval1 eval x
 <span class="ocamlkeyword">let</span> <span class="ocamlkeyword">rec</span> eval x = eval2 eval x ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> plus : 'a -&gt; 'b -&gt; [&gt; `Plus <span class="ocamlkeyword">of</span> 'a * 'b ] = &lt;<span class="ocamlkeyword">fun</span>&gt;
<span class="ocamlkeyword">val</span> eval2 : ('a -&gt; int) -&gt; [&lt; `Num <span class="ocamlkeyword">of</span> int | `Plus <span class="ocamlkeyword">of</span> 'a * 'a ] -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;
<span class="ocamlkeyword">val</span> eval : ([&lt; `Num <span class="ocamlkeyword">of</span> int | `Plus <span class="ocamlkeyword">of</span> 'a * 'a ] <span class="ocamlkeyword">as</span> 'a) -&gt; int = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>To make this even more comfortable, you may use type definitions as
abbreviations for or-patterns. That is, if you have defined <span class="c003">type myvariant = [`Tag1 of int | `Tag2 of bool]</span>, then the pattern <span class="c003">#myvariant</span> is
equivalent to writing <span class="c003">(`Tag1(_ : int) | `Tag2(_ : bool))</span>.</p><p>Such abbreviations may be used alone,


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f = <span class="ocamlkeyword">function</span>
   | #myvariant -&gt; <span class="ocamlstring">"myvariant"</span>
   | `Tag3 -&gt; <span class="ocamlstring">"Tag3"</span>;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : [&lt; `Tag1 <span class="ocamlkeyword">of</span> int | `Tag2 <span class="ocamlkeyword">of</span> bool | `Tag3 ] -&gt; string = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>


or combined with with aliases.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> g1 = <span class="ocamlkeyword">function</span> `Tag1 _ -&gt; <span class="ocamlstring">"Tag1"</span> | `Tag2 _ -&gt; <span class="ocamlstring">"Tag2"</span>;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> g1 : [&lt; `Tag1 <span class="ocamlkeyword">of</span> 'a | `Tag2 <span class="ocamlkeyword">of</span> 'b ] -&gt; string = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> g = <span class="ocamlkeyword">function</span>
   | #myvariant <span class="ocamlkeyword">as</span> x -&gt; g1 x
   | `Tag3 -&gt; <span class="ocamlstring">"Tag3"</span>;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> g : [&lt; `Tag1 <span class="ocamlkeyword">of</span> int | `Tag2 <span class="ocamlkeyword">of</span> bool | `Tag3 ] -&gt; string = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div>
<h3 class="subsection" id="ss:polyvariant-weaknesses"><a class="section-anchor" href="#ss:polyvariant-weaknesses" aria-hidden="true"></a>4.2.1  Weaknesses of polymorphic variants</h3>
<p>After seeing the power of polymorphic variants, one may wonder why
they were added to core language variants, rather than replacing them.</p><p>The answer is twofold. 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.</p><p>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.</p><p>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.</p><p>Beware also that some 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.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">type</span> abc = [`A | `B | `C] ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">type</span> abc = [ `A | `B | `C ]</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f = <span class="ocamlkeyword">function</span>
   | `As -&gt; <span class="ocamlstring">"A"</span>
   | #abc -&gt; <span class="ocamlstring">"other"</span> ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : [&lt; `A | `As | `B | `C ] -&gt; string = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>
<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f : abc -&gt; string = f ;;</div>



<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> f : abc -&gt; string = &lt;<span class="ocamlkeyword">fun</span>&gt;</div></div>

</div><p>


You can avoid such risks by annotating the definition itself.


</p><div class="caml-example toplevel">

<div class="ocaml">



<div class="pre caml-input"> <span class="ocamlkeyword">let</span> f : abc -&gt; string = <span class="ocamlkeyword">function</span>
   | <span class="ocamlhighlight">`As</span> -&gt; <span class="ocamlstring">"A"</span>
   | #abc -&gt; <span class="ocamlstring">"other"</span> ;;</div>



<div class="pre caml-output error"><span class="ocamlerror">Error</span>: This pattern matches values of type [? `As ]
       but a pattern was expected which matches values of type abc
       The second variant type does not allow tag(s) `As</div></div>

</div>
<hr class="footnoterule"><dl class="thefootnotes"><dt class="dt-thefootnotes">
<a id="note1" href="#text1">1</a></dt><dd class="dd-thefootnotes"><div class="footnotetext">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 (<span class="c003">-nolabels</span>
options) is now deprecated for normal use.</div></dd></dl>
<hr>
<a href="objectexamples.html"><img src="previous_motif.svg" alt="Previous"></a>
<a href="index.html"><img src="contents_motif.svg" alt="Up"></a>
<a href="polymorphism.html"><img src="next_motif.svg" alt="Next"></a>
</body>
</html>