Erlang Central

Filtering Lists

Revision as of 12:50, 23 November 2006 by 213.171.204.166 (Talk)

Problem

You have a list with a bunch of items, but you want to have a copy of that list with some items removed.

Solution

lists:filter, in Erlang's standard library, allows you to filter a list based on a predicate.

1> lists:filter(fun(X) -> X rem 2 /= 0 end, [1,2,3,4,5,6,7,8,9,0]).
[1,3,5,7,9]
2> lists:filter(fun(X) -> is_list(X) end, [14,"abc",["xyz"|23]]).
["abc",["xyz"|23]]

You can supply your own predicate, as well. Here we filter a list of numbers that are greater than some limit we've defined:

3> lists:filter(fun(X) -> X > 12 end,
3>     lists:map(fun(Y) -> Y * Y end, [1,2,3,4,5,6,7,8])).
[16,25,36,49,64]

Erlang ships with a few versions of filter in the lists module, along with variants such as mapfoldl that allow you to combine a map and foldl operation into a single pass.

For the best efficiency in your programs, you should review the existing functionality in the lists module to see if there are any combined functions that could reduce the amount of list traversal in your application.