how can i remove the first two elements and the last two elements from a list?

You should not reuse L1 and L in the same list. You need an extra variable here:

delelements(L, R) :-
    append(M, [_, _], L),
    append([_, _], R, M).

So here M is a list that contains the elements of L, except for the last two. R is a variant of M, except that the first elements are removed.

This then give us:

?- delelements([1,4,1,3,0,2,2,5], R).
R = [1, 3, 0, 2] ;

Furthermore we do not need to use append/3 [swi-doc] to remove a fixed number of elements from the head. We can use unification for this:

delelements(L, R) :-
    append([_, _ | R], [_, _], L).

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top