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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With