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

/ Erlang.LIstRecipeFiltering

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

Filtering Lists

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]

Discussion

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.


Comments about this recipe

Contributors

Based on work by NoelWelsh and GordonWeakliem.

-- BrentAFulgham - 29 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder: 060

 
 
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