Edit Prolog program to output the result of a computation

Viewed 38

I've found something about this in other questions, but mine is a bit different.

Given a string, I have to output another string with no adjacent duplicates.

E.g., given [a,a,b,b,c,d,a], my output will be [a,b,c,d,a].

Now, I've wrote the following recursive program to check if a certain given string has adjacent duplicates:

notequal(A,[]).

notequal(A,[X|S]) :- not(A=X).

noadj([]):-!.

noadj([A|S]) :- notequal(A,S), noadj(S).

How would I modify it in order to output what I described? I've tried multiple times but I'm new to prolog and I can't seem to get into its logic.

Of course, I'll need another variable, which would contain an element if notequal is true for that element. So my idea is to iterate through the list and only add a certain term to the result if it passes the "notequal" test.

I'll edit this: I finally managed to do something like that by adding

noadjlist([X|S],[X|LS]) :- notequal(X,S), noadjlist(S,LS).

noadjlist([X|S],LS) :- noadjlist(S,LS).

noadjlist([],LS):-!.

However, my results are like:

?- noadjlist([1,2,2,3],LS).

LS = [1, 2, 3|_19316] .

why do I get that uninstantiated variable at the end?

1 Answers
noadjlist([],LS):-!.

should be

noadjlist([],[]):-!.
Related