Home > Software design >  Delete an element at a specified index, return untouched list if given negative or 0 as an index
Delete an element at a specified index, return untouched list if given negative or 0 as an index

Time:04-21

Hi I really am needing help with this Prolog problem. I want to delete an element at a specified index but only when given an index that is greater than 0. If the index is 0 or less, I would like to just return the list untouched.

For example:

delete(List,Index,NewList).   
?-L=[1,2,3,4],delete(L,2,L2),write(L2).
L2 = [1,3,4]

for <= 0:

delete(List,Index,NewList).   
?-L=[1,2,3,4],delete(L,-1,L2),write(L2).
L2 = [1,2,3,4]

I have managed to handle the first case using the following code.

remove([_|T], 1, T).
remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).

I attempted using prologs if-else equivalent syntax but was not able to get it working.

EDIT: Thank you so much for the responses! I did not realize I was missing another case.

CodePudding user response:

You just need to include one more base case in the predicate definition:

remove(L, N, L) :-
    N =< 0.
remove([_|T], 1, T).
remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).

Examples:

?- L = [one, two, three, four], remove(L, 2, R).
L = [one, two, three, four],
R = [one, three, four] ;
false.

?- L = [one, two, three, four], remove(L, -1, R).
L = R, R = [one, two, three, four] ;
false.

CodePudding user response:

You just need another rule for handling N =< 0:

remove(L, N, L) :-
    N =< 0.

remove([_|T], 1, T).

remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).
  • Related