Search code examples
listprologunification

Prolog, access specific member of list?


Can anyone tell me how to access a specific member of a list in prolog? Say for example I need to access the 3rd or 4th element of a list passed into a rule?


Solution

  • nth0(Ind, Lst, Elem) or nth1(Ind, Lst, Elem) with SWI-Prolog, nth0 the first element has the index 0.

    For example,

    nth0(3, [a, b, c, d, e], Elem). %Binds d to Elem
    nth1(3, [a, b, c, d, e], Elem). %Binds c to Elem
    
    nth0(Ind, [a, b, c, d, e], d).  %Binds 3 to Ind
    nth0(3, [a, b, c, X, e], d).    %Binds d to X
    
    nth0(3, [a, b, c, d, e], c).    %Fails.