Erlang Central

Filter All Elements Matching a Certain Criteria

Revision as of 02:34, 31 August 2006 by Cyberlync (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


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 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,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, List1).
% Example of lists:takewhile
4> lists:takewhile(fun(X) -> X < 5 end, List1).

Erlang has excellent support for list processing.