| Difference Topic ListListMinus (r1.1 - 29 Aug 2004 - BrentAFulgham) |
| Added: | ||||
| > > |
%META:TOPICINFO{author="BrentAFulgham" date="1093765536" format="1.0" version="1.1"}%
Finding Elements in One Array but Not AnotherProblemYou want to find elements that are in one list but not another.SolutionYou want to find elements in listA that aren't in list B. Erlang provides several ways of doing this:
Use the
The | |||
1> A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]. [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] 2> B = [2,4,6,8,9,10,12,14,15,16]. [2,4,6,8,9,10,12,14,15,16]. 3> lists:subtract(A,B). [1,3,5,7,11,13] |
++) and subtraction (--). The subtraction operator provides the same functionality as the lists:subtract function:
4> A -- B. [1,3,5,7,11,13] |
lists:foreach function), and filter out any entries from list A that are also members of list B.
5> lists:foldl(fun(X,ACC) -> Y=lists:member(X, B), 5> if Y -> [X|ACC]; 5> true -> ACC 5> end end, [], lists:reverse(A)). [2,4,6,8,9,10,12,14,15,16] |