Reputation: 295
I have this program in Prolog, it removes elements at each nth element from a list, like: removenth([1,2,3,4,5,6], 2, R). it should return : R = [1,3,5].
I have this:
removeallNth(F, N, R):- removeallNth(F, N, 1, R).
removeallNth([], _, _, R).
removeallNth([H|T], N, C, R):- N \== C, Nc is C + 1, concat(R,H,S),
removeallNth(T, N, Nc, S).
removeallNth([_|T], N, C, R):- N == C, removeallNth(T, N, 1, R).
The problem is that it returns true instead of R = [1,3,5]. I checked in SWI-Prolog debugger and it arrives to the correct result but then it keeps checking stuff. I understand it has to do with unification but I don't know how to apply it.
Upvotes: 2
Views: 701
Reputation: 22585
Consider this modification to your program:
removeallNth(F, N, R):- removeallNth(F, N, 1, R).
removeallNth([], _, _, []).
removeallNth([H|T], N, C, [H|R]):-
N \== C, Nc is C + 1,
removeallNth(T, N, Nc, R).
removeallNth([_|T], N, C, R):-
N == C,
removeallNth(T, N, 1, R).
In the first clause of removeallNth/4 you have to return an empty list.
In the second clause of removeallNth/4 you don't need to do the concat, you just have to return add the item in the list returned in the 4th argument of the head of that clause.
Upvotes: 4