Search code examples
listprologmember

Get elements which are not in second list


What I'm trying to accomplish is to get what 'Components' are not being used. So I created a list with all the 'Components' and 'In Use Components'.
My idea is to compare this lists and create another list with the elements that didn't match.

component('name 1', 1).
component('name 2', 2).
component('name 3', 3).
component('name 4', 4).
component('name 5', 5).

inUse(1, 'name 1').
inUse(1, 'name 3').
inUse(1, 'name 5').

comp_list(L):- findall(Comp, component(Comp, _), L).
inuse_list(L):- findall(Comp, inUse(_, Comp), L).

I don't know how to do something like this: member('name comp', List). where I can replace 'name comp' with every element of the other list.

Thanks in advance.

Example:

L1 = ['name 1', 'name 2', 'name 3', 'name 4', 'name 5'] %comp_list(L).
L2 = ['name 1', 'name 3', 'name 5']                     %inuse_list(L).

someRule(R):- comp_list(L1), inuse_list(L2),    %more code, to obtain a list R with:

R = ['name 2', 'name 4'] (Elements lacking on inuse_list)

Solution

  • You could add a simple recursive predicate to obtain elements of comp_list that are not member of inuse_list:

    obtain_elements([],_,[]).
    obtain_elements([H|T],L,[H|T1]):-\+member(H,L),obtain_elements(T,L,T1).
    obtain_elements([H|T],L,L2):-member(H,L),obtain_elements(T,L,L2).
    

    and use it like:

    someRule(R):- comp_list(L1),
                  inuse_list(L2), 
                  obtain_elements(L1,L2,R).
    

    OR another way using findall/3 predicate:

    someRule(R):- comp_list(L1),
                  inuse_list(L2), 
                  findall(X,(member(X,L1),\+member(X,L2)),R).