Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the filter function in Haskell?

I have a haskell program to list all integers from [1..n] based on the input n. I want to filter certain numbers based on a condition from it and display as a list. where and how can I use the filter function / condition?

According to haskell documentation:

filter :: (a -> Bool) -> [a] -> [a]

filter, applied to a predicate and a list, returns the list of those elements that satisfy the predicate; i.e.,

filter p xs = [ x | x <- xs, p x]
like image 995
Amjad Avatar asked Jan 03 '12 12:01

Amjad


2 Answers

You got it, pretty much. So the rest of the deal is designing the predicate function for your list. Assuming you already had a list called xs and a predicate function p, all you'd have to do is

filter p xs. 

Often, you'll see p defined as an anonymous, or lambda, expression, like so:

filter (\n -> n \`mod\` 2 == 0) xs. 

It is not necessary, and it might be helpful as a beginner to define named functions.

isEven n = n \`mod\` 2 == 0  evenListNumbers xs = filter isEven xs  evenListNumbers [1,2,3,4] 

Which is this [2,4].

So a predicate function for a given list filter takes a list element and returns a boolean value. If it's true, the element is retained (or added to the resulting list), and if it's false, it is passed over.

like image 60
Sarah Avatar answered Sep 25 '22 17:09

Sarah


Well, you transform that condition into a predicate (a function returning Bool) and use it to filter the numbers.

For example, if you have to select only the odd numbers you can use filter odd [1..n]

like image 31
Mihai Maruseac Avatar answered Sep 23 '22 17:09

Mihai Maruseac