September 17, 2026

Haskell for Hobos -- making types: data and type

There is a thing called "newtype", but it is unusual with special surprises, so we devote an entire chapter to it.

If you want to make a new type, "data" is the first thing to reach for:

data Animal = Pig | Cow | Sheep
 -- or --
data Animal = Pig | Cow | Sheep deriving(Show)
Here we have our new type "Animal" with three possible values. This is a lot like a C enumeration type. You can imagine that Haskell Bool is defined like this. Notice how deriving(Show) is appended in the second example. This allows us to use the "show" function to convert the type to a string.

In the above, "Pig", "Cow", and "Sheep" are called type constructors. We can have a type where type constructors also have arguments. It is fairly common to have a type that has just one type constructor with several arguments:

data Coord = Coord int int 
The above defines a type with a type constructor that has two arguments, both integer. Notice that the type and the type constructor have the same name, which is common, but not required. We would use this like so:
xy = Coord 13 66
This is somewhat like a C struct, and we can make it even more so by using what is called record syntax:
data Item = Item {
	name :: String ,
	count :: Int
}
Here we give names to fields, as well as assigning them types. Haskell gives us accessor functions for free to get values when we do this. We might use them like so:
dingus = Item "potato" 13
np = count dingus
Record syntax also lets us create a type like this:
zz = Item {species = "dog", count = 13}
This can avoid confusion with types that have many fields.

Using "type" to create synonyms

This is not a useful as you might hope. You can assign a new name to a type, but it does not rename the type constructors. This is fine for primitive types like "Int" or enumeration like types such as our Animal type above.

Mostly this allows some clarity by giving names to primitive types, such as:

type Coord = Float
data Vector = Vector Coord Coord
Note that type names must begin with capital letters.


Have any comments? Questions? Drop me a line!

Tom's software pages / tom@mmto.org