Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Haskell's filter

I understand that Haskell's filter is a high order function (meaning a function that takes another function as a parameter) that goes through a list checking which element fulfills certain boolean condition.

I don't quite understand its definition:

filter:: (a->Bool)->[a]->[a]
filter p [] = []
filter p (x:y) | p x = x:filter p y
               | otherwise = filter p y

I understand that if I pass an empty list to the function, it would just return an empty list, but how do I read the last two lines?

like image 393
andandandand Avatar asked Apr 02 '10 17:04

andandandand


1 Answers

It uses guards which if you are coming from a language with a C style syntax are a bit similar to the switch structure.

The last pattern reads: If the function p evaluates to true with the argument x then return the head of the list and the filtered tail of the list. Otherwise just return the filtered tail of the list.

You could also rewrite it like so:

filter p (x:y) = if (  p x ) then
                     x:filter p y
                 else
                     filter p y
like image 50
Yacoby Avatar answered Sep 30 '22 18:09

Yacoby