General
Material
Lecture 1
Lecture 2
Lecture 3
Lecture 4
Lecture 5

Solution

%% We need two base clauses for stopping the recursion. This one is
%% reached when the list does not contain any occurrences of the
%% element that is supposed to be removed. In this case, the empty
%% list is reached at some point. And the empty list is returned as
%% result.
remove(_,[],[]).

%% If the element which is supposed to be removed is the head of the
%% list, we remove the head. Hence, the result is the tail.
%% We put a cut to tell Prolog that it does not need to search for any
%% alternatives because we found and removed one element matching the
%% specification. If there are other such elements later in the list,
%% we don't care, and they should not be removed.
remove(X,[X|Tail],Tail) :- !.

%% If the head does not match the specified term X, try to remove an
%% element matching X from the tail of the list. The output of the
%% predicate is constructed by sticking the head back onto OutTail
%% (which is the result of removing X from the tail of the input list).
remove(X,[Head|InTail],[Head|OutTail]) :-
                        remove(X,InTail,OutTail).
    

Back to the exercise.