Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all instances of an item in a list :Prolog

Tags:

prolog

removeAll(X, [ X | T], [ H1 | T1 ] ):-
      ( member ( X , T )
        -> removeAll ( X , T , [ H1 | T1 ] )
        ;[ H1 | T1 ] is T
      ).
removeAll ( X , [ H | T ] , L ):-
removeAll ( X , T , L2 ), append ( [ H ] , L2 , L ).

If i pass "removeAll(2,[1,1,2],L).",
it gives the error "ERROR: is/2: Type error: 'evaluable' expected, found '[]' (an empty_list)".

If i pass "removeAll(1,[1,1,2],L)." , it returns false.

Really confused. Where am i going wrong ?

like image 521
Yogesh kumar Avatar asked Jan 29 '26 05:01

Yogesh kumar


1 Answers

First, you must consider the case that the source list is empty:

removeAll(_, [], []).

This is also the stop condition. Cause you are building a recursive predicate, deleting every element in the Head of the target list that match a specific element, until the list is empty

Second clause, if the element is the Head of the List, don't copy it to the Result list, and continue the recursive call with the Tail.

removeAll(X, [X|T], L):- removeAll(X, T, L), !.

Third clause, copy the element in the Head of the list to the Result list, and continue with the recursive call with the Tail.

removeAll(X, [H|T], [H|L]):- removeAll(X, T, L ).

Your predicate:

removeAll(_, [], []).
removeAll(X, [X|T], L):- removeAll(X, T, L), !.
removeAll(X, [H|T], [H|L]):- removeAll(X, T, L ).
like image 163
Yasel Avatar answered Feb 01 '26 16:02

Yasel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!