Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top