UserMeli
UserMeli

Reputation: 43

Predicate to check whether an element is behind another element in a list

Given is a List and two Elements. First I needed to check whether the two elements are part of the list.Afterwards, check whether an Element Elem2
comes after Elem1 in the given List. The predicate I am using is weiterHinten with 3 arguments.

For Example: check if c is after b in the list [a,c,b,a].

weiterHinten([H|T],H,B).
weiterHinten([H|T],A,B):-weiterHinten(T,A,B).

weiterHinten([a,c,b,a],b,c).

This goal would need to return false.I know, that after I find the Header of the list to be equals to A I would need to check if B is a member of the Tail of the List. If it is, it means that B is after A in the list, but I am unsure how to do this.

I tried:

weiterHinten([H|T],H,B):-member(B,T). 

But whenever I was calling the goal it was always returning true for me no matter if Elem2 was after Elem1

Upvotes: 2

Views: 667

Answers (1)

user7610
user7610

Reputation: 28811

Leave the weiterHinten([H|T],H,B). rule out. This is a syntactic shortcut for weiterHinten([H|T],H,B) :- true. and that is nonsense.

This is working for me:

weiterHinten([H|T],H,B) :- member(B, T).
weiterHinten([H|T],A,B) :- weiterHinten(T,A,B).

The results are

| ?- weiterHinten([a,c,b,a],b,c).

no
| ?- weiterHinten([a,b,c,a],b,c).

true

Upvotes: 1

Related Questions