listprologunificationprolog-dif

Deleting all members of a list without unification in Prolog


Possible Duplicate:
Prolog delete: doesn't delete all elements that unify with Element

In Prolog if you write this:

delete([(1,1),(1,2),(1,1),(3,4)],(1,_),L).

the result will be:

L = [ (1, 2), (3, 4)].

What is normal because the _ variable binds with 1 in the first element and it searches for further elements of (1,1) and deletes them.

Is there a way to prevent this unification from happening and deleting all members of the form (1,_). In that case the result must be: L = [ (3, 4)].


Solution

  • delete_pattern([], _, []).
    delete_pattern([H|T], P, O) :-
        (    H \= P
        ->   O = [H|O1],
             delete_pattern(T, P, O1)
        ;    delete_pattern(T, P, O) ).
    

    You may like to use other predicates for filtering that would result in slightly different semantics as ==/2 or =@=/2.