简体   繁体   中英

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?

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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM