cani
cani

Reputation: 91

Prolog: Remove all elements from lister higher than X

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

Answers (3)

Matej
Matej

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:

  1. Construct a base case, usually empty lists.
  2. Try to recurse to the bottom of the recursion and on the way, only keep the desired elements. Here, keeping means that you recurse with the unwanted elemements removed.
  3. For it to "grow back together" properly, as in, when the recursion goes back up, you have to properly define the output list.

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

CapelliC
CapelliC

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

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

Related Questions