Re: Problem with code to find element in list - instantiation



The following code does the trick (more or less):

value([First|_], 0, First).
value([_|Rest], Pos, Value) :-
value(Rest, Pos1, Value),
Pos is Pos1+1.

Not exactly what you wrote though, as it does not bind the third argument to 'no element' if given an incorrect position, but fails instead. Seemed like a better solution to me, shouldn't be to hard to adapt...

Btw, there should be a built-in predicate that does this. E.g. in Sicstus Prolog this is nth/3, in SWI Prolog nth0/3 or nth1/3, etc

Greets,
Peter


none schreef:
Hello, I'm trying to write a predicate that will allow to get a value a given List position.

example:

value([a,b,c],3,R).

would say R = c.

This works properly with the following code:

value([], _, 'no element').
value([First|Rest], 0, First).
value([First|Rest, Position, Value) :-
First \== Value,
Position >= 0,
Position2 is Position -1,
value(Rest, Position2, Value).

However the code doesn't work the other way around. For example:

value([a,b,c],X,c).

doesn't give X = 3
and outputs an error saying that

! Instantiation error in argument 1 of >= /2
! goal: _81>=0

wich makes sense since the compiler doesn't know the value of Position so it can calculate if it's >= 0.

Any ideias on howto solve this?

Thanks.
.