Delete/filter elements from a list

What is an easy way to delete elements from the list which are >5.

I have this solution:
delete_element(_,,).
delete_element(E,[E|R],RL) :-
delete_element(E,R,RL).
delete_element(E,[X|R],[X|RL]) :-
X=E, delete_element(E,R,RL).

Console Example:
?- L= [10,3,5,7,9], delete_element(E,L,RL)->E>5.
L = [10, 3, 5, 7, 9],
E = 10,
RL = [3, 5, 7, 9].

But that only checks the first element of the list. Please help!

The way you’ve written the predicate only checks the first element, because you ask that E unify with each element in the list, but that unification can only succeed for the first entry, because the numbers are different.

I think the easiest way to do this would be to pass a goal that determines which elements to include or remove, like exclude/3
e.g.

?- exclude([X]>>(X > 5), [10, 3, 5, 7, 9], RL).
RL = [3, 5].

(also using library(yall) there, but you could also write that as

greater_than_five(X) :- X > 5.

?- exclude(greater_than_five, [10, 3, 5, 7, 9], RL).
1 Like

library(yall) is great but in this particular case you don’t really need it. You can write:

?- exclude(<(5), [10,3,5,7,9], R).
R = [3, 5].
3 Likes

And for those who prefer to not use “list comprehensions”:

delete_gt_5([], []).
delete_gt_5([X|Xs], Ys) :-
    (  X > 5
    -> Ys = Ys2
    ;  Ys = [X|Ys2]
    ),
    delete_gt_5(Xs, Ys2).
1 Like