John Gann
John Gann

Reputation: 605

Trying to get a list element by index in prolog

This is what I have so far:

getByIndex([X],0,E):- E is X.
getByIndex([H|_],0,E):- E is H.
getByIndex([_|T],I,E) :- getByIndex(T,I-1,E).

It seems to work when requesting the first element, but not subsequent elements, and I can't quite figure out why.

I'm aware that there might be a built-in solution in something like SWI-prolog, but I'd like to understand why this fails.

Upvotes: 0

Views: 3282

Answers (1)

Continuum
Continuum

Reputation: 88

getByIndex([X], 0, X).
getByIndex([H|_], 0, H).
getByIndex([_|T], I, E) :- NewIndex is I-1, getByIndex(T, NewIndex, E).

Two things: "E is X" is not the same as "E=X". is/2 is used to evaluate a mathematical expression, while =/2 is unification.

Secondly, when you are using I-1 in getByIndex(T,I-1,E), the second argument is being unified with I-1, which means that X is literally "I-1". To avoid that you should create a temporary variable NewIndex, and use is/2 to calculate I-1.

Upvotes: 3

Related Questions