1
votes

I want to write a program which deletes every Nth element from a list without the last one. My program is already working fine and gives me the correct result, but when I ask for another result, prolog comes with the error ">/2: Arguments are not sufficiently instantiated". Here is the code I have so far:

delete_elements([],0,[]).
delete_elements([],_,[_|_]).
delete_elements(L,N,R) :-
    length(L,LL),
    LL > N,
    nth1(N,L,_,RZ),
    NZ is N + 1,
    delete_elements(RZ,NZ,RR),
    R = RR.
delete_elements(L,N,R) :-
    length(L,LL),
    LL =< N,
    delete_elements([],_,R),
    L = R.

I think that there is something wrong with the cancellation condition of the recursion. How to fix this?

Thanks in advance!

1

1 Answers

1
votes

The problem is in the clause:

delete_elements(L,N,R) :-
    length(L,LL),
    LL =< N,
    delete_elements([],_,R),
    L = R.

You have finished your work but you still call your predicate with an anonymous variable instead of N. You could just write:

delete_elements(L,N,L) :-
    length(L,LL),
    LL =< N.

Example:

?- delete_elements([1,2,3,4,5,6,7,8,9,1,2,3],3,L).
L = [1, 2, 4, 6, 8, 1, 3] ;
false.

For what you asked in your comment my implementation would be:

 delete_elements(L,N,R) :- delete_elements(L,1,N,R).

delete_elements([],_,_,[]).
delete_elements([X],N,N,[X]).
delete_elements([X|Xs],N,N,Rs):- length([X|Xs],Y),Y>1,delete_elements(Xs,1,N,Rs).
delete_elements([X|Xs],P,N,[X|Rs]):- P < N,P1 is  P+1,delete_elements(Xs,P1,N,Rs).