next up previous
Next: More About Lists Up: The Frightened Freshers Guide Previous: Trees

Polymorphic Functions

While you may wish to define lots of different functions to do many things, there are some eventualities that require you to have functions that will do things in a more general sense. An example is summing up all elements in a list. The big problem with this example is that if you tried to feed it Strings then it would probably fall over fairly spectacularly.

If this datatype is defined:
\begin{lstlisting}
data List a = Nil \vert Cons a (List a)
\end{lstlisting}

Then it is possible to do the following:
\begin{lstlisting}
append :: List a -> List a -> List a
append Nil ys = ys
append (Cons x xs) ys = Cons x (append xs ys)
\end{lstlisting}

Because this is a very general definition for a (i.e a can of be any data type you wish) the function here is possible. Note that because both are of type a both lists must be of the same type, you could not add a list of Bools to a list of Ints here.



Tom Carlson 2006-04-11