Type Synonyms and newtype Wrappers

Explore two alternatives to creating simple types with data: type synonyms and newtype wrappers.

So far, we have learned to create custom types using data declarations. They are especially useful for creating types with several alternative constructors or so-called sum types. In the case where our types can be constructed in only one way, there are two simpler alternatives we can apply.

Type synonyms

In the previous lessons we made use of the Coordinates type that represents a location in 2D space.

data Coordinates = Coordinates Double Double

In the end, we are using our Coordinates type similar to a tuple of two doubles. We even defined a Show instance for it that prints coordinates like a tuple of doubles. At this point why not simply use (Double, Double) instead?

Well for one, it can make type annotations (and error messages) more expressive. Let’s take for example the type signature of a distance function.

distance :: Coordinates -> Coordinates -> Double

From reading the type annotation, it is intuitively clear that distance will compute the distance in space between two coordinates. It is certainly a bit more clear than:

distance :: (Double, Double) -> (Double, Double) -> Double

However, to obtain this advantage, we do not have to create a new type. We can also choose to create a type synonym for (Double, Double) instead. This can be achieved using the type keyword.

type Coordinates = (Double, Double)

This type synonym declaration does not create a new type. Instead, it introduces a new name for the existing type (Double, Double), and they can now be used interchangeably. So, we can define our distance function as:

Get hands-on with 1200+ tech skills courses.