(This is NOT a coursework question. Just my own personal learning.)
I’m trying to do an exercise in Prolog to delete elements from a list. Here’s my code :
deleteall([],X,[]).
deleteall([H|T],X,Result) :-
H==X,
deleteall(T,X,Result).
deleteall([H|T],X,[H|Result]) :- deleteall(T,X,Result).
When I test it, I first get a good answer (ie. with all the Xs removed.) But then the backtracking offers me all the other variants of the list with some or none of the instances of X removed.
Why should this be? Why do cases where H==X ever fall through to the last clause?
The last clause says that when removing
Xfrom a list, the head element may stay (independently of its value). Prolog mayuse this clause at any time it sees fit, independently of whether the condition in the preceding clause is true or notbacktrack into this clause if another clause fails, or if you direct it to do so (e.g. by issuing;in the top-level to get the next solution). If you add a condition that the head element may not equalX, it should work.Edit: Removed the incorrect assertion I originally opened with.