Get an element in a list at a specified index

Viewed 66

I need to write a program that return an element from a list, using a specified index.

We have a list of the English alphabet X = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]

Starting at 0, I have to return, for example, the number with index 13, so the letter 'n', how do you return an element from a list with a specified index?

Here's what I have worked in, but still doesn't run properly.

position(0, 0, [], a).
position(X, I, [H1|T1], _):-
    position(X, I1, T1, H1),
    I = I1 + 1.
2 Answers

It's just a matter of iterating over the list and counting as you go. Try something like this:

select( [X|_]  , 0 , X ) .
select( [_,Xs] , N , C ) :- N > 0 , N1 is N-1, select(Xs,N1,C).

or

select( Xs , N , C ) :- select(Xs,0,N,C) .

select( [X|_]  , N , N , X ) .
select( [_|Xs] , V , N , C ) :- V1 is V+1, select(Xs,V1,N,C).

The latter will work in a more Prolog-like way, bi-directionally. It doesn't care if you specified an index or not:

  • select( [a,b,c,d] , N , C ) successively succeeds with
    • N=0, C=a
    • N=1, C=b
    • N=2, C=c
    • N=3, C=d
  • select( [a,b,c,d] , 2 , C ) succeeds with just
    • C=c
  • select( [a,b,c,d] , N , d ) succeeds with just
    • N=3

My approach is also "count the number down and match the thing from the front when it reaches zero":

:- use_module(library(clpfd)).

position(0, [Elem|_], Elem).
position(Pos, [_|T], Elem) :-
    Pos #= Pos_ + 1,
    position(Pos_, T, Elem).

Your request "a program that return an element from a list, using a specified index" is an imperative request like you might use in Python; taking a single index and returning a single element. Changing to a Prolog relational way of thinking brings you to Nicholas Carey's comment:

will work bi-directionally. It doesn't care if you specified an index or not

So you can give an element and get an index. As well as that, they can check whether an element is at an index; this confirms 'dog' is in position 3, and says 'cow' is not in position 3:

?- position(3, [apple,box,cat,dog], dog).
true

?- position(3, [apple,box,cat,dog], cow).
false

On backtracking, find all positions of an element, this finds 'box' in two places:

?- position(Pos, [apple,box,cat,dog,box], box).
Pos = 1 ;
Pos = 4

Which means compared to Python this code overlaps with x = items[i] and i = items.index(x) and enumerate(items) and items[i] == x.

Related