e r l a n g : c o o k b o o k

/ Erlang.ListListMinus

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Finding Elements in One Array but Not Another

Problem

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

Solution

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

Use the lists:subtract Function

The lists module provides the subtract function, which takes two list and returns a new copy of the first list, such that the first occurrence of each element of the second list is removed. For example:

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]
Note: Erlang provides native list operators for concatentation (++) and subtraction (--). The subtraction operator provides the same functionality as the lists:subtract function:
4> A -- B.
[1,3,5,7,11,13]

Iterate over the two lists

You can iterate over the two lists (using the 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]

Discussion


Comments about this recipe

Contributors

Based on work by IvanHernandez.

-- BrentAFulgham - 29 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder: 040

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest