Prolog, access specific member of list?

David Carpenter picture David Carpenter · Oct 17, 2012 · Viewed 37.3k times · Source

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?

Answer

joel76 picture joel76 · Oct 17, 2012

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.