Selecting Elements with Filter

Introduction to Filtering

Welcome to the third unit of our course! Imagine you have a large basket of apples, but you only want to bake a pie using the ripe ones. You would look at each apple, apply a rule ("Is it ripe?"), keep the ones that pass the test, and set aside the rest.

In programming, we often need to do exactly this with our data. We want to keep specific elements from a list based on a certain rule, discard the rest, and preserve the original order of the items we kept. In Haskell, the perfect tool for this job is a built-in function called filter. Throughout this lesson, we will learn how to use filter to cleanly and easily select the exact data we need.

Here is the type signature for filter:

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

This tells us that filter takes a predicate — a function from an element type a to Bool — and a list of a values. It returns another list of the same element type a, because it keeps or discards existing items rather than changing them.

Quick Recall: map vs. filter

Before we look closely at filter, let us take a moment to remember what we learned in the previous lesson. You might recall that we used the map function to apply a change to every single item in a list. For example, map can take a list of numbers and transform it into a list of doubled numbers. map is all about transforming data.

The filter function is different. It does not change or transform the items at all. Instead, it selects them.

To make this selection, filter relies on what is called a predicate. A predicate is simply a function that asks a yes-or-no question. In Haskell terms, a predicate is a function that returns a Bool (either True or False). filter goes through a list item by item, applies the predicate function to each item, and keeps only the ones that return True.

Using filter with Built-in Predicates

Let us see filter in action. The filter function needs two arguments to do its job: a predicate (our True/False rule) and the list we want to search through.

Haskell has several built-in predicates we can use right away. One of them is even, which takes a number and returns True if the number is even.

Here is how we can combine filter and even to pick out the even numbers from a list of numbers 1 through 10:

Haskell
evens :: [Int]
evens = filter even [1 .. 10]

In this code, we create a list of integers called evens. We tell filter to use the even rule on the list [1 .. 10]. It checks 1 (False, discard), then 2 (True, keep), then 3 (False, discard), and so on.

If we were to print the evens list, the output would be:

[2,4,6,8,10]

Notice how the numbers we kept are still in their original order, and nothing has changed — we just dropped the odd numbers.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal