Search code examples
prolog

How to access an element in a list in Proplog?


In prolog, how do I access an element in a list with an index? For example, I'm writing a rule get_i(List, I, X) where List is the list I'm passing in, I is the index, and X is the element that will be returned. A sample run could be like: getget_i([a,b,c,d], 3, X).
The output will be c

Thanks


Solution

  • Assuming the point of the exercise is to figure out how to find the nth element of a list...

    The easy way is something like this, where the zeroth element of the list is the head of the list, and you just recursively discard the head of the list and decrement N until N reaches 0.

    nth( [H|_] , 0 , H ) .
    nth( [_|T] , N , H ) :- N > 0, N1 is N-1, nth(T,N1,H).
    

    But that doesn't allow you to invoke it in different ways:

    • nth([a,b,c,d,e],N,d). fails.
    • nth([a,b,c,d,e],N,X). fails.

    Doing things correctly, though, is hardly more complicated:

    nth( L , N , H ) :- nth(L,0,N,H) .
    
    nth( [H|_] , N , N , H ) .
    nth( [_|T] , M , N , H ) :- var(N)     ,         M1 is M+1 , nth(T,M1,N,H) .
    nth( [_|T] , M , N , H ) :- integer(N) , M < N , M1 is M+1 , nth(T,M1,N,H) . 
    

    Now nth([a,b,c,d,e],N,X) will repeatedly succeed on backtracking yielding

    N = 0, X = a
    N = 1, X = b
    N = 2, X = c
    N = 3, X = d
    N = 4, X = E
    

    and nth([a,b,c,d,e],N,d) yields

    N = 3