Erlang Thursday – lists:any/2

Today’s Erlang Thursday function of the week is lists:any/2.

lists:any/2 takes a predicate function as the first argument, and a list to iterate over as its second argument. lists:any/2 returns true if the predicate function returns true for any of the elements in the given list, otherwise, lists:any/2 returns false.

lists:any(fun erlang:is_atom/1, [1, 2, 3, 4, 5, 6, 7]).
% false
lists:any(fun erlang:is_atom/1, [1, 2, 3, 4, a, 6, 7]).
% true
lists:any(fun erlang:is_atom/1, [{1, 2}, 3, 4, a, 6, 7]). 
% true
lists:any(fun(X) -> X rem 2 == 1 end, [1, 2, 4]).
% true
lists:any(fun(X) -> X rem 2 == 1 end, [0, 2, 4]).    
% false

lists:any/2 is eager, and will return with a result of true as soon as it is found, and will ignore processing the rest of the list.

timer:tc(lists, any, [fun(X) -> X rem 2 == 1 end, lists:seq(2, 200000, 2)]).
% {248410,false}
timer:tc(lists, any, [fun(X) -> X rem 2 == 0 end, lists:seq(2, 200000, 2)]).
% {13,true}

The lists module also contains a function lists:all/2, similar to lists:any/2, but checks if the predicate function returns true for every element in the supplied list.

lists:all(fun erlang:is_number/1, [1, 2, 3, 4, a, 6, 7]).
% false
lists:all(fun erlang:is_number/1, [1, 2, 3, 4, 5, 6, 7]).
% true

lists:all/2 is also eager, and will return with a result of false as soon as it is found, and will ignore processing the rest of the list.

timer:tc(lists, all, [fun(X) -> X rem 2 == 0 end, lists:seq(2, 200000, 2)]).
% {235276,true}
timer:tc(lists, all, [fun(X) -> X rem 2 == 1 end, lists:seq(2, 200000, 2)]).
% {14,false}

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *