Erlang Central

Difference between revisions of "Filtering Lists"

From ErlangCentral Wiki

m
Line 23:Line 23:
  
 
[[Category:CookBook]][[Category:ListRecipes]]
 
[[Category:CookBook]][[Category:ListRecipes]]
 +
 +
 +
 +
[http://www.magical-casino.com/casino_download.html Casino Downloading Action.]
 +
[http://www.gambling-online-theory.com/casinos/fun-casinos.html fun casinos]
 +
[http://www.magical-casino.com/casino_download.html Casino Downloading Action.]
 +
[http://www.gambling-online-theory.com/online-casino/bet-online-casino.html bet online casino]
 +
[http://www.casino-games-wiki.com/index.php/casino_games_rules casino games rules]
 +
[http://www.gambling-online-theory.com/casinos/on-line-casinos.html on line casinos]
 +
[http://www.casino-theory.com/online-casino-royale/play-free-online-casino.html play free online casino]
 +
[http://www.gambling-online-theory.com/casinos/casinos-strategy.html casinos strategy]
 +
[http://www.gambling-online-theory.com/casinos-portal/best-casinos-online.html best casinos online]
 +
[http://www.casino-games-wiki.com/index.php/play_casino_games play casino games]

Revision as of 11:32, 23 November 2006

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]

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.


Casino Downloading Action. fun casinos Casino Downloading Action. bet online casino casino games rules on line casinos play free online casino casinos strategy best casinos online play casino games