Lecture 19-1
Custom Types
There are two ways to make types in Haskell.
The type
Keyword
The type
keyword gives a new name to an existing type.
- All types must start with capital letters.
type String' = [Char]
exclaim :: String' -> String'
exclaim str = str + "!"
> exclaim "hello"
> "hello!!
Type is useful when you want to give a meaningful name to a complex type.
type VoteResults = [(Int,String)]
results :: VoteResults
The data
Keyword
The data
keyword is used to create an entirely new type.
data Bool' = True | False
|
should be read as OR.- Each of the values is a constructor.
- Each constructor should start with a capital letter.
To find out more about a type you can use the GHCI :info
command. For more information about a type constructor then you can use the type
command.
Example
data Direction = North | South | East | West
rotate North = East
rotate East = South
rotate South = West
rotate West = North
> :t rotate
> rotate :: Direction -> Direction
Type Classes
By default, a new data type is not part of any type class. This means that running rotate
will give an error. As is GHCI doesn’t know how to show
it.
We can use the deriving
keyword to fix this:
data Direction = North | South | East | West deriving (Show)
This will automatically put the type into the class Show
and will allow it to print to the prompt.
Hakell can automatically implement the following type classes:
Show
- Will print out the type as it is in the code.
Read
- Will parse the type as it is in the code.
Eq
- The natural definition of equality.
Ord
- Constructors that come first are smaller.
You can add these to the tuple that deriving takes as input. You should include all type classes that make sense for your type so that you can use the functions you want.
Exercises
type Marks = (String, [Int])
data Colour = Red | Blue | Green deriving (Show, Read)
-
toRGB :: Colour -> (Float, Float, Float) toRGB Red = (1,0,0) toRGB Green = (0,1,0) toRGB Blue = (0,0,1)
You should note that as this type isn’t in the class
eq
then you can’t use guard and equality testing on it.