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 intThe 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 66This 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 dingusRecord 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.
Mostly this allows some clarity by giving names to primitive types, such as:
type Coord = Float data Vector = Vector Coord CoordNote that type names must begin with capital letters.
Tom's software pages / tom@mmto.org