Erlang Central

Finding Elements in One Array but Not Another

From ErlangCentral Wiki


You want to find elements that are in one list but not another.


You want to find elements in list A that aren't in list B. Erlang provides several ways of doing this:

Use lists:subtract/2 , or the equivalent -- operator.

1> A = lists:seq(1,16).
2> B = lists:seq(2,16,2).
3> lists:subtract(A,B).
4> A -- B.

Iterate over the two lists

You can iterate over the two lists, and filter out any entries from list A that are also members of list B.

5> lists:foldr(fun(X,Acc) -> Y=lists:member(X, B),
5>    if Y -> [X|Acc];
5>    true -> ACC
5> end end, [], A).
6> lists:filter(fun (X) -> not lists:member(X,B) end, A).