J. Doe
J. Doe

Reputation: 77

Get index of given element in list

I am trying to solve some basic puzzles to learn prolog. I am trying to get the index of a given element in a list with recursion. I got stuck trying to solve the problem and I am not sure why. When I execute this it only returns "false" instead of the index.

elem(_, [], 0).

elem(E, [E | T], RES) :-
    elem(E, T, CUR_RES), RES is CUR_RES + 1. 

An example query I use to check the code elem(2, [1, 2], X).

Upvotes: 1

Views: 435

Answers (1)

Guy Coder
Guy Coder

Reputation: 24976

Your problem with

elem(2, [1, 2], X).

is that when it tries to unify with the base case

 elem(_, [], 0).

it fails because the second parameter is not empty.

When it tries to unify with the recursive case

elem(E, [E | T], RES) :-
    elem(E, T, CUR_RES), 
    RES is CUR_RES + 1.

E is 2, which requires the list to be [2|T] but since the list is [1,2] it also can not unify.

This is closer to what you want

elem(E,[E|_],0).

elem(E,[_|T],Res) :-
    elem(E,T,Cur_rest),
    Res is Cur_rest + 1.

Example runs:

?- elem(2, [1, 2], X).
X = 1 ;
false.

?- elem(1, [1, 2], X).
X = 0 ;
false.

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

You need to do the matching for the value you are seeking in the base case and not the recursive case. Once you do that the rest of changes follow as needed.

Upvotes: 1

Related Questions