Search code examples
prologdpll

How to remove a variable out of a list of variables in prolog?


I wanna implement the DPLL algorithm. Therefore i have to remove all occurrencies of a variable in a list of other variables, e.g. deleting neg(X) out of [neg(X), pos(X), neg(Y), pos(Y)] should return [pos(X), neg(Y), pos(Y)]. I've tried some built-in predicates like exclude/3 or delete/3 but all left me with asuming X = Y and a result [pos(X), pos(Y)], with all neg(_) removed, but I only want neg(X) removed and not neg(Y). Is this somehow possible?


Solution

  • From the Logtalk library list object:

    delete([], _, []).
    delete([Head| Tail], Element, Remaining) :-
        (   Head == Element ->
            delete(Tail, Element, Remaining)
        ;   Remaining = [Head| Tail2],
            delete(Tail, Element, Tail2)
        ).
    

    Sample call:

    ?- delete([neg(X), pos(X), neg(Y), pos(Y)], neg(X), Rest).
    Rest = [pos(X), neg(Y), pos(Y)].
    

    The key is to use the standard ==/2 term equality predicate instead of the standard =/2 unification predicate.