Skip to content
November 20, 2010 / dranaxum

filter in Haskell vs filterING in C#

If you are both a Haskell and C# programmer then you should be familiar to the filter function in Haskell and the filtering functions in C# (Find,FindAll etc).

Example of filter in Haskell

-- the type of filter is : filter :: (a->Bool)->[a]->[a] which means that 
-- filter takes a function as an argument and a list and aplies the function to all the elements of the list
-- when the function returns true then the element will be added to the resulting list.
findAllOddElements :: [Int] -> [Int]
findAllOddElements ls 
  = filter odd ls

The same code which does the exact same thing in C# would look like this

List<int> findAllOddElements(List<int> a)
  return a.FindAll(
    delegate(int elem) {
      return elem%2==1;

We can see that the two functions are very similar, both requiring a function passed as a parameter. However, internally, they work different because Haskell is a functional programming language.
Hence filter is defined like this:

filter:: (a->Bool) -> [a] -> [a]
filter f [] = []
filter f (l:ls)
  | f l = l : filter f ls
  | otherwise = filter f ls

There is a nicer way to define findAllOddElements in C# using Linq like this:

List<int> findAllOddElements(List<int> a)
  return a.Where(elem => elem%2==1).ToList();

Assuming the resulting list is not empty then the function Find in C# should be equivalent to the following function in Haskell:

findAllOddElements :: [Int] -> Int
findAllOddElements ls 
  = head (filter odd ls) 

Of course you can use function composition and partial application:

findAllOddElements :: [Int] -> Int
  = head . (filter odd) 

Also we can rewrite the Find function in C# using the Where prototype:

int findAllOddElements(List<int> a)
  return a.Where(elem => elem%2==1).ToList()[0];

Hopefully you will find this post usefull!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: