Reputation: 91
I am trying to write a prolog program that will remove all elements in a list higher than the value X
.
For example, I want to remove all elements higher than 50
from this list:
[2,8,18,34,40,44,46,51,52,54,64,66,76,90]
So I get:
[2,8,18,34,40,44,46]
Upvotes: 2
Views: 1625
Reputation: 625
It would be nice to see how far you've gotten. What is giving you problems?
The idea in most of these problems usually goes something like this:
There are really two ways to this. Either remove elements when going down, or ignore them when going back up. These are in essence the same.
I'm not the best at explaining this. I will simply post my solution. But I strongly suggest you give it your best before looking at it. :)
delete_gt([], _, []) :- !.
delete_gt([Head|Rest], X, L) :-
Head > X, !,
delete_gt(Rest, X, L).
delete_gt([Head|Rest], X, [Head|L]) :-
delete_gt(Rest, X, L).
Upvotes: 3
Reputation: 60034
You could also consider this utility from apply library
del_elems_higher :-
exclude(condition, [2,8,18,34,40,44,46,51,52,54,64,66,76,90], L), writeln(L).
condition(X) :- X > 50.
test:
?- del_elems_higher.
[2,8,18,34,40,44,46]
Upvotes: 0
Reputation: 21990
Using accumulator
removeHigherThan( X, List, Ans) :-
removeHigherThan( X, List, Ans, [] ), !.
removeHigherThan( _, [], Ans, Ans).
removeHigherThan( X, [H | Tail], Ans, Acc ) :-
(
( H > X, NewEl = [] )
;
( H =< X, NewEl = [H] )
),
append( Acc, NewEl, NewAcc ),
removeHigherThan( X, Tail, Ans, NewAcc).
It works like that
?- removeHigherThan(10, [1,4], X).
X = [1, 4].
?- removeHigherThan(10, [1,12,4], X).
X = [1, 4].
Upvotes: 0