| 1 |
= TypeConstructor |
| 2 |
|
| 3 |
In <<StandardML#,Standard ML>>, a type constructor is a function from |
| 4 |
types to types. Type constructors can be _nullary_, meaning that |
| 5 |
they take no arguments, as in `char`, `int`, and `real`. |
| 6 |
Type constructors can be _unary_, meaning that they take one |
| 7 |
argument, as in `array`, `list`, and `vector`. A program |
| 8 |
can define a new type constructor in two ways: a `type` definition |
| 9 |
or a `datatype` declaration. User-defined type constructors can |
| 10 |
can take any number of arguments. |
| 11 |
|
| 12 |
[source,sml] |
| 13 |
---- |
| 14 |
datatype t = T of int * real (* 0 arguments *) |
| 15 |
type 'a t = 'a * int (* 1 argument *) |
| 16 |
datatype ('a, 'b) t = A | B of 'a * 'b (* 2 arguments *) |
| 17 |
type ('a, 'b, 'c) t = 'a * ('b -> 'c) (* 3 arguments *) |
| 18 |
---- |
| 19 |
|
| 20 |
Here are the syntax rules for type constructor application. |
| 21 |
|
| 22 |
* Type constructor application is written in postfix. So, one writes |
| 23 |
`int list`, not `list int`. |
| 24 |
|
| 25 |
* Unary type constructors drop the parens, so one writes |
| 26 |
`int list`, not `(int) list`. |
| 27 |
|
| 28 |
* Nullary type constructors drop the argument entirely, so one writes |
| 29 |
`int`, not `() int`. |
| 30 |
|
| 31 |
* N-ary type constructors use tuple notation; for example, |
| 32 |
`(int, real) t`. |
| 33 |
|
| 34 |
* Type constructor application associates to the left. So, |
| 35 |
`int ref list` is the same as `(int ref) list`. |