Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an element in a list at a specified index

I need your help! Can you help me with this: delete an element in a list at a specified index in Prolog.

For example:

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

I don't know how to do this.

Solved!

   away([G|H],1,H):-!.
   away([G|H],N,[G|L]):- N > 1, Nn is N - 1,!,away(H,Nn,L).
   ?-away([1,2,3,4,5],3,X), write(X). 
like image 912
Tanya Avatar asked Apr 27 '13 09:04

Tanya


People also ask

How do I remove an element from an ArrayList at a specific index?

The remove(int index) method present in java. util. ArrayList class removes the element at the specified position in this list and shifts any subsequent elements to the left (i.e. subtracts one from their indices).

How do I remove a position from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


1 Answers

Use the built-in function nth0/4 (which uses 0-based indexing) or nth1/4 (which uses 0-based indexing) to do this. In your case, since you use 1-based indexing, nth1 should be used:

nth1(Index, List, _, Remainder)

Supply Index and List, since you don't need the deleted element, you can ignore it, then the resulting list will be in Remainder.

This is the source code of nth1 taken from lists.pl library in SWI-Prolog, rewritten to remove dependency:

% Case 1: Index not specified
nth1(Index, In, Element, Rest) :-
    var(Index), !,
    generate_nth(1, Index, In, Element, Rest).
% Case 2: Index is specified
nth1(Index, In, Element, Rest) :-
    integer(Index), Index > 0,
    find_nth1(Index, In, Element, Rest).

generate_nth(I, I, [Head|Rest], Head, Rest).
generate_nth(I, IN, [H|List], El, [H|Rest]) :-
    I1 is I+1,
    generate_nth(I1, IN, List, El, Rest).

find_nth1(1, [Head|Rest], Head, Rest) :- !.
find_nth1(N, [Head|Rest0], Elem, [Head|Rest]) :-
    M is N-1,
    find_nth1(M, Rest0, Elem, Rest).
like image 179
nhahtdh Avatar answered Oct 15 '22 16:10

nhahtdh