Amjad
Amjad

Reputation: 1687

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]

Upvotes: 25

Views: 78895

Answers (2)

Sarah
Sarah

Reputation: 6695

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.

Upvotes: 39

Mihai Maruseac
Mihai Maruseac

Reputation: 21435

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]

Upvotes: 2

Related Questions