Dragon
Dragon

Reputation: 73

Prolog predicate that returns a list after checking for element

I am new to prolog. I am trying to write a predicate that accepts an element and list and checks to see the occurrence of the element in the list and returns the rest of the list after the element.
Example is mypredicate(3, [1 2, 3, 4, 5, 6, 7]) returns [3, 4, 5, 6, 7].
I hope I am able to explain.

mypredicate(X, [X|_]).
mypredicate(X, [_|T]) :- mypredicate(X,T).

This is basically just checking if the element is there in the list. How do I write a rule that returns the rest of the list after X?

Upvotes: 1

Views: 2112

Answers (2)

CapelliC
CapelliC

Reputation: 60034

you should add a third argument

mypredicate(X,[X|L],[X|L]).
mypredicate(X,[_|T],L) :- mypredicate(X,T,L).

If you're interested only to the first occurrence of X and L, add a cut at the first rule:

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

Another way, use a library(lists) predicate:

edit corrected after comment by @tim.newport

mypredicate(X,L,[X|T]) :- append(_,[X|T],L).

Upvotes: 2

coder
coder

Reputation: 12992

You need to return all the list in the base case like:

mypredicate(X, [X|T],[X|T]).

Also the clause:

 mypredicate(X, [_|T]) :- mypredicate(X,T).

is used when the head of the list is X, so you need to make sure that in this case the head is different from X like:

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

Upvotes: 2

Related Questions