I'm pretty new at SML and I would like to make sure I really know the basics. What is the difference between type and datatype in SML, and when to use which?
3 Answers
type
declarations just give another name to an existing type. Declaring type t = int * int
simply means that you can now write t
instead of int * int
- it doesn't actually provide any functionality.
datatype
definitions let you create brand new types by introducing new data constructors. Data constructors are the keywords and symbols you use to create and pattern-match values, such as the list type's nil
and ::
. There's nothing particularly special about those identifiers; you can define them yourself as easily as this:
datatype 'a list = nil | :: of 'a * 'a list

- 19,816
- 3
- 51
- 63
-
4One nit: `nil` and `::` are _data_ constructors. A type constructor is a _type_ with parameters, e.g. `list` itself. – Andreas Rossberg Feb 04 '14 at 21:29
Datatypes in sml can have more than one type, e.g.
datatype a = SomeType | SomeOtherType
You can use them when type-checking, e.g.
fun doThings (var : a) : bool =
case var of
(SomeType) => true
(SomeOtherType) => false

- 199
- 1
- 5
You may think of it as this: types are for opaque and atomic types, while datatype
are for type with constructors, and so, which can be destructured, mainly within pattern matching on expressions.
A datatype
may expose a simple type view too, if it implements an opaque type (declared with type
in a signature and defined as a datatype
in a structure implementing the signature).
Atomic type like int
and word
may be seen as destructurable types in some respect, like with Peano arithmetic interpretation of numbers, but SML's int
, word
and the not so well called real
, are primitive types.

- 6,870
- 6
- 52
- 56