How to calculate the index of an item in a list?

I'm starting to play with the prologue, and from the Java background it is really difficult for me, so here is a stupid question:

How do you write the predicate indexOf, able to assign the index of this element to this list?

My first question is about the arity predicate: I think it should be 3, for example:

indexOf(List,Element, Index) :- ...... 

I'm right? It may already exist in the built-in libraries, but I want to learn how to write it. Thank you for your help.

+7
prolog
source share
3 answers

You can do this recursively: suppose the index is based on 0 (otherwise just change the value 0 to 1 in the first sentence)

 indexOf([Element|_], Element, 0). % We found the element indexOf([_|Tail], Element, Index):- indexOf(Tail, Element, Index1), % Check in the tail of the list Index is Index1+1. % and increment the resulting index 

If you only want to find the first appearance, you can add a cut (!) To avoid backtracking.

 indexOf([Element|_], Element, 0):- !. indexOf([_|Tail], Element, Index):- indexOf(Tail, Element, Index1), !, Index is Index1+1. 
+11
source share

It is recommended to use tail recursion:

 indexOf(V, [H|T], A, I) :- Value = H, A = I, ! ; ANew is A + 1, indexOf(V, T, ANew, I) . indexOf(Value, List, Index) :- indexOf(Value, List, 0, Index) . indexOfWithoutFailure(Value, List, Index) :- indexOf(Value, List, 0, Index) ; Index = -1 . 

Some sample queries:

 ?- indexOf(d, [a, b, c, d, e, f], Index). Index = 3. ?- indexOf(x, [a, b, c, d, e, f], Index). false. ?- indexOfWithoutFailure(x, [a, b, c, d, e, f], Index). Index = -1. 

If you want to get all the indices of an element in the list, you must write another predicate for it without a slice named allIndexesOf or something like that.

+1
source share

I did this in the following notation, and this is pretty concise and neat:

 index([V|_],V,0). index([_|T],V,s(I)) :- index(T,V,I). 

output:

 ?- index([a,b,c,a],a,X). X = 0 ; X = s(s(s(0))) ; false. ?- index(List,a,s(0)). List = [_G1710, a|_G1714]. 
0
source share

All Articles