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