Search code examples
listprolog

Prolog Remove element from list


I have the following fact to remove all occurences of a element in a list. Although the output is correct, the element is just replaced for a blank space

remover( _, [], []).
remover( R, [R|T], [T2]) :- remover( R, T, T2).
remover( R, [H|T], [H|T2]) :- H \= R, remover( R, T, T2).

When I call remover the output is :

remover(3,[1,2,3,4,3],Res)
Res = [1, 2, [4, []]]

I also have the following fact to remove only the first occurence but the output is the same from above

remover_primeira( _, [], []).
remover_primeira( R, [R|T], [T2]) :-remover_primeira( R, T, T2),!.
remover_primeira( R, [H|T], [H|T2]) :- H \= R, remover_primeira( R, T, T2).

What am I doing wrong?


Solution

  • You should not wrap T2 in a singleton list in the second clause, it should be:

    remover( _, [], []).
    remover( R, [R|T], T2) :- remover( R, T, T2).
    remover( R, [H|T], [H|T2]) :- H \= R, remover( R, T, T2).

    In case you only need to remove the first occurrence, then you should not recurse from the moment you found that element:

    remover( _, [], []).
    remover( R, [R|T], T).
    remover( R, [H|T], [H|T2]) :- H \= R, remover( R, T, T2).