next up previous
Next: Map and Filter Up: The Frightened Freshers Guide Previous: Polymorphic Functions

More About Lists

Note that the ListInt and List datatypes that have been defined earlier on in this set of pages can be used, although it is far easier and shorter to write out lists using the shorthand in square brackets. The first line of the old style first defines a list type using the algebraic data type, the second line is the list itself. The two other examples are both examples of the built in polymorphic list type; The first one is a list of Strings and the second a list of Ints.


\begin{lstlisting}
-- Old Style
data ListInt = Nil \vert Cons Int ListInt
Cons 1...
...is is a'',''List'',''Of Strings'']
-- Another Example
[1,2,3,4]
\end{lstlisting}

When it comes to patten matching on lists like this, it is fairly simple:


\begin{lstlisting}
addListOfIntegers :: [Int] -> Int
addListOfIntegers [] = 0
addListOfIntegers [x:xs] = 1 + addListOfIntegers xs
\end{lstlisting}

Note that the haskell prelude already has a function a little bit like this for finding the number of elements in a list simply called length:


\begin{lstlisting}
Hugs.Base> :t length
length :: [a] -> Int
Hugs.Base> length [''hello'',''world'']
2
\end{lstlisting}



Tom Carlson 2006-04-11