next up previous
Next: Recursion Up: The Frightened Freshers Guide Previous: Types in Haskell

Enumerated Types

The season datatype shown below has four elements, each seperated by a pipe symbol. This declaration is known as a `Data Constructor'.


\begin{lstlisting}
data Season = Spring \vert Summer \vert Autumn \vert Winter
\end{lstlisting}

And another example:
\begin{lstlisting}
data Temp = Hot \vert Cold
\end{lstlisting}

Now, using these two user-defined datatypes we can make a function that will, when fed a season, will return if that season is generally hot or cold.
\begin{lstlisting}
Weather :: Season -> Temp
Weather Spring = Cold
Weather Summer = Hot
Weather Autumn = Cold
Weather Winter = Cold
\end{lstlisting}

This is known as Pattern Matching and is very, very useful indeed! What if we want to return a String from a Season? Well, we could do:
\begin{lstlisting}
show Spring = ''Spring''
\end{lstlisting}
but that is bad because the data constructor itself already has something build in to handle this kind of thing.


\begin{lstlisting}
data Season = Spring \vert Summer \vert Autumn \vert Winter
deriving(Show, Eq, Ord)
\end{lstlisting}

Wow, what on earth does that mean? Well, we know that Season is a datatype that has four elements. The deriving part has three distinct little bits. Show converts whatever Season to a String when required. Eq stands for Equality and allows testing if two seasons are the same. Ord means this datatype is ordered and two seasons can be compared to see which is bigger. The code below shows examples of this.
\begin{lstlisting}
Winter == Winter - would return True
Winter >= Spring - would return True
\end{lstlisting}

Here is another example using the Shape datatype defined in lectures and classes.
\begin{lstlisting}
data Shape = Circle Float \vert Rectangle Float Float
derivi...
... Bool
isRound (Circle r) = True
isRound (Rectangle h w) = False
\end{lstlisting}

Interestingly, the Bool (True or False) is just another datatype. You can ask hugs about the type of these and they are in fact ordered!
\begin{lstlisting}
Hugs.Base> :t True
True :: Bool
Hugs.Base> :t False
False :...
...
Hugs.Base> False > True
False
Hugs.Base> False == False
True
\end{lstlisting}

From this we can say that the datatype Bool is probably defined something like this (Although in reality it is probably something different.)


\begin{lstlisting}
data Bool = False \vert True
deriving(Show,Eq,Ord)
\end{lstlisting}


next up previous
Next: Recursion Up: The Frightened Freshers Guide Previous: Types in Haskell
Tom Carlson 2006-04-11