e r l a n g : c o o k b o o k

/ Erlang.ListFilterElements

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Finding All Elements in a List Matching Certain Criteria

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]

Discussion

Erlang has excellent support for list processing.


Comments about this recipe

Contributors

Based on work by IvanHernandez.

-- BrentAFulgham - 29 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder: 030

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest