My confusion mainly lies around understanding singleton variables.
I want to implement the predicate noDupl/2
in Prolog. This predicate can be used to identify numbers in a list that appear exactly once, i. e., numbers which are no duplicates. The first argument of noDupl
is the list to analyze. The
second argument is the list of numbers which are no duplicates, as described below.
As an example, for the list [2, 0, 3, 2, 1]
the result [0, 3, 1]
is computed (because 2
is a duplicate).
In my implementation I used the predefined member predicate and used an auxiliary predicate called helper.
I'll explain my logic in pseudocode, so you can help me spot where I went wrong.
- First off, If the first element is not a member of the rest of the list, add the first element to the new result List (as it's head).
- If the first element is a member of
T
, call the helper method on the rest of the list, the first elementH
and the new list. Helper method, if
H
is found in the tail, return list withoutH
, i. e.,Tail
.noDupl([],[]). noDupl([H|T],L) :- \+ member(H,T), noDupl(T,[H|T]). noDupl([H|T],L) :- member(H,T), helper(T,H,L). helper([],N,[]). helper([H|T],H,T). %found place of duplicate & return list without it helper([H|T],N,L) :- helper(T,N,[H|T1]).%still couldn't locate the place, so add H to the new List as it's not a duplicate
While I'm writing my code, I'm always having trouble with deciding to choose a new variable or use the one defined in the predicate arguments when it comes to free variables specifically. Thanks.
noDupl([a,a,a], Xs)
? - false