Erlang Thursday – lists:filter/2

Today’s Erlang Thursday is on lists:filter/2.

lists:filter/2 takes two arguments, a predicate function and a list to iterate over. The return value is a list of items for which the predicate function returns true for that item.

lists:filter(fun (X) -> X rem 2 =:= 1 end, [1, 2, 3, 4, 5]).
% [1,3,5]
lists:filter(fun erlang:is_atom/1, [1, a, 3, {a, b}, 'World', foo]).
% [a,'World',foo]
lists:filter(fun (X) -> X > 0 end, [1, 0, -3, foo, -13, 43]).
% [1,foo,43]
lists:filter(fun (X) -> X > 0 end, []).                      
% []
lists:filter(fun (X) -> false end, [1, 2, 3, 4, 5]).
% []
lists:filter(fun (X) -> true end, [1, 2, 3, 4, 5]). 
% [1,2,3,4,5]

–Proctor

1 thought on “Erlang Thursday – lists:filter/2

  1. Pingback: Erlang Thursday – lists:dropwhile/2Proctor It | Proctor It

Comments are closed.