next up previous
Next: Thanks To... Up: The Frightened Freshers Guide Previous: More About Lists

Map and Filter

These are two higher order functions that operate on lists and are very useful indeed! They perform quite different tasks.

Map performs an action on a list. If we had a list of integers, we can add three to the whole list in one very simple step:


\begin{lstlisting}
mapDemo :: [Int] -> [Int]
mapDemo [] = []
mapDemo x = map (+3) x
\par
Main> mapDemo [1,2,4,6]
[4,5,7,9]
\end{lstlisting}

If you feed this function a list of Integers, it will spit out a list of integers with all the elements three higher than previously.

Filter is different in that it will return a list that has had a boolean operation performed on each element in the list and any False results would be removed from the list. This is useful if you wish to filter out invalid values from a list, play with sets of numbers and remove some that do not match a certain condition and so on. The example below shows a use of filter.


\begin{lstlisting}
filterDemo :: [Int] -> [Int]
filterDemo [] = []
filterDemo x = filter (>4) x
\par
Main> filterDemo [1,3,5,6,7]
[5,6,7]
\end{lstlisting}



Tom Carlson 2006-04-11