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.