Finding Elements in One Array but Not Another
From Erlang Community
(Difference between revisions)
| Revision as of 14:58, 24 September 2006 (edit) Ayrnieu (Talk | contribs) (minor language; use lists:foldr/3 instead of lists:foldr/3+lists:reverse/1 (!); use lists:filter/2; remove bogus+bizarre reference to lists:foreach/2; use lists:seq/2+3; actually filter as described) ← Previous diff |
Current revision (15:01, 24 September 2006) (edit) (undo) Ayrnieu (Talk | contribs) m (typo) |
||
| Line 29: | Line 29: | ||
| 5> end end, [], A). | 5> end end, [], A). | ||
| [1,3,5,7,9,11,13,15] | [1,3,5,7,9,11,13,15] | ||
| - | 6> lists:filter(fun (X) -> not lists: | + | 6> lists:filter(fun (X) -> not lists:member(X,B) end, A). |
| [1,3,5,7,9,11,13,15] | [1,3,5,7,9,11,13,15] | ||
| </code> | </code> | ||
Current revision
[edit] Problem
You want to find elements that are in one list but not another.
[edit] Solution
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). [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] 2> B = lists:seq(2,16,2). [2,4,6,8,10,12,14,16]. 3> lists:subtract(A,B). [1,3,5,7,9,11,13,15] 4> A -- B. [1,3,5,7,9,11,13,15] |
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). [1,3,5,7,9,11,13,15] 6> lists:filter(fun (X) -> not lists:member(X,B) end, A). [1,3,5,7,9,11,13,15] |

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

