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?
As data type already represents the type of value that can be stored so values can directly be assigned to the data type variables. On other hand in case of data structure the data is assigned to using some set of algorithms and operations like push, pop and so on.
The unit type can be used as the parameter type and/or return type of a function that performs side effects and don't need to take or return (respectively) any information.
A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error.
A parameterized datatype is a recipe for creating a family of related datatypes. The type variable 'a is a type parameter for which any other type may be supplied. For example, int List is a list of integers, real List is a list of reals, and so on.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With