prologvisual-prolog

Prolog. Delete even indexes from list


I try to delete elements with even indexes. Here is my code:

DOMAINS
    list = integer*
PREDICATES
    remove(list,list)
CLAUSES 
    remove([],[]).

    remove([_,H|T1], [H|T2]):-
        remove(T1, T2).

GOAL
    remove([1,2,3,4,5], NewList).

I miss the first item in the list, and save the second in a new list NewList. But it's working good only when the length of list is even number.

What am I missing? Maybe my approach wrong?


Solution

  • Yes, your predicate only works for a list with an even number of elements. The first clause of remove/2 is for the empty list (no elements), the second clause is for lists with two or more elements. You then pass on the rest, without the two elements at the front.

    In the case of a list with an odd number of elements, you need a base case of a list with exactly one element. The logic is, if you start counting the indexes at 0, you have: