Erlang Central

Filter All Elements Matching a Certain Criteria

From ErlangCentral Wiki


From a list, you want only the elements that match certain criteria.

This notion of extracting a subset of a larger list is common. It's how you find all engineers in a list of employees, all users in the "staff" group, or all the filenames you're interested in.


Use the lists module's filter or dropwhile functions. The filter function takes a list and a predicate, and returns a list of all elements where the predicate is true.

% Example of lists:filter
1> List = lists:seq(1,16).
2> lists:filter(fun(X) -> X rem 2 == 0 end, List).

The dropwhile function scans through a list, dropping elements until it reaches the first element satisfying some criteria; at this point, it returns the remaining elements of the list. The takewhile function does the opposite, taking elements until some criteria is met, and dropping the rest.

% Example of lists:dropwhile (uses same List as before)
3> lists:dropwhile(fun(X) -> X < 5 end, List).
% Example of lists:takewhile
4> lists:takewhile(fun(X) -> X < 5 end, List).

Erlang has excellent support for list processing.