Erlang Central

Difference between revisions of "Filter All Elements Matching a Certain Criteria"

From ErlangCentral Wiki

 
Line 28: Line 28:
  
  
[[Category:CookBook]]
+
[[Category:CookBook]][[Category:ListRecipes]]

Revision as of 22:43, 3 September 2006

Problem

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.

Solution

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].
[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).
[2,4,6,8,10,12,14,16]

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

Erlang has excellent support for list processing.