Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How compute Index of element in a list?

Tags:

prolog

I am starting to play with prolog, and with a Java background it's really difficult for me so here is a silly question:

How will you write an indexOf predicate able to give the index of a given element in a given list ?

My first question is about the predicate arity: I guess it should be 3 such as:

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

Am I right ? May be this already exists in built-in libraries but I want to learn how to write it. Thanks for your help.

like image 393
Manuel Selva Avatar asked Dec 07 '10 19:12

Manuel Selva


People also ask

How do you find the index value of a element in a list Python?

To facilitate this, Python has an inbuilt function called index(). This function takes in the element as an argument and returns the index. By using this function we are able to find the index of an element in a list in Python.

How do you get the index of an element in a list in Java?

The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for.


1 Answers

You can do it recursively: Suppose 0-based index (otherwise just change the 0 with 1 on the first clause)

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 want only to find the first appearance, you could add a cut (!) to avoid backtracking.

indexOf([Element|_], Element, 0):- !.
indexOf([_|Tail], Element, Index):-
  indexOf(Tail, Element, Index1),
  !,
  Index is Index1+1.
like image 53
gusbro Avatar answered Sep 18 '22 12:09

gusbro