Backport from sid to buster
[hcoop/debian/mlton.git] / doc / guide / src / ProductType.adoc
CommitLineData
7f918cf1
CE
1ProductType
2===========
3
4<:StandardML:Standard ML> has special syntax for products (tuples). A
5product type is written as
6[source,sml]
7----
8t1 * t2 * ... * tN
9----
10and a product pattern is written as
11[source,sml]
12----
13(p1, p2, ..., pN)
14----
15
16In most situations the syntax is quite convenient. However, there are
17situations where the syntax is cumbersome. There are also situations
18in which it is useful to construct and destruct n-ary products
19inductively, especially when using <:Fold:>.
20
21In such situations, it is useful to have a binary product datatype
22with an infix constructor defined as follows.
23[source,sml]
24----
25datatype ('a, 'b) product = & of 'a * 'b
26infix &
27----
28
29With these definitions, one can write an n-ary product as a nested
30binary product quite conveniently.
31[source,sml]
32----
33x1 & x2 & ... & xn
34----
35
36Because of left associativity, this is the same as
37[source,sml]
38----
39(((x1 & x2) & ...) & xn)
40----
41
42Because `&` is a constructor, the syntax can also be used for
43patterns.
44
45The symbol `&` is inspired by the Curry-Howard isomorphism: the proof
46of a conjunction `(A & B)` is a pair of proofs `(a, b)`.
47
48
49== Example: parser combinators ==
50
51A typical parser combinator library provides a combinator that has a
52type of the form.
53[source,sml]
54----
55'a parser * 'b parser -> ('a * 'b) parser
56----
57and produces a parser for the concatenation of two parsers. When more
58than two parsers are concatenated, the result of the resulting parser
59is a nested structure of pairs
60[source,sml]
61----
62(...((p1, p2), p3)..., pN)
63----
64which is somewhat cumbersome.
65
66By using a product type, the type of the concatenation combinator then
67becomes
68[source,sml]
69----
70'a parser * 'b parser -> ('a, 'b) product parser
71----
72While this doesn't stop the nesting, it makes the pattern significantly
73easier to write. Instead of
74[source,sml]
75----
76(...((p1, p2), p3)..., pN)
77----
78the pattern is written as
79[source,sml]
80----
81p1 & p2 & p3 & ... & pN
82----
83which is considerably more concise.
84
85
86== Also see ==
87
88* <:VariableArityPolymorphism:>
89* <:Utilities:>