Search code examples
prolog

Get an element in a list at a specified index


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.

Solution

  • 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