How do I use the filter function in Haskell?

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.

Leave a Comment

tech