erp
erp

Reputation: 3014

index of element

I'm new to s.o and new to Prolog which is what i am working on, specifically SWI-Prolog. I am trying to do as the title says, and have gotten it to work on a 1 based list (starting at 1 instead of zero) using some methods that were included in the SWI-library. and this is my code:

indexof(I,E,L):-
   nth1(I,L,E).
   indexof(-1,_,_).

My assignment (yes it's hw -_-) is to do this but as a 0 based count i tried on the last line to add I is I - 1 but i kept getting errors. Is there any other way to get it into a 0 based count?

so for this indexof(A,a,[w,x,y,z,a]). i should get 4 but am getting 5.

Upvotes: 3

Views: 1117

Answers (2)

Tovar
Tovar

Reputation: 455

The definition of nth1/3 is nth1(?Index, ?List, ?Elem). The ? means that the argument doesn't have to be instantiated, so Prolog will fill it for you, and that means you don't even have to make a new predicate for the purpose! Here's an example for using the built-in nth1/3 predicate this way:

?- nth1(I, [1,2,3,1,3,4,5], 1).
I = 1 ;
I = 4 ;
false.

?- nth1(I, [1,2,3,1,3,4,5], 2).
I = 2 ;
false.

?- nth1(I, [1,2,3,1,3,4,5], 3).
I = 3 ;
I = 5 ;
false.

Upvotes: 0

mndrix
mndrix

Reputation: 3188

SWI-Prolog has nth0/3 which is just like nth1/3 but the index starts at 0.

To make your original approach work, you need something like:

indexof(I,E,L) :-
    nth1(I1,L,E),
    I is I1 - 1.

Prolog variables can only be assigned once. If you tried I is I - 1, you're claiming that I is itself minus 1. That's never true, so the predicate fails. You need to use an intermediate variable, like I1 in the example above.

Upvotes: 2

Related Questions