Prolog, access specific member of list?

45,347

Solution 1

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.

Solution 2

When the indexes you need to access are so small, you could use pattern matching. Say we need the third element or fourth:

third([_,_,E|_], E).
fourth([_,_,_,E|_], E).

This could be more useful if used 'inline', when the list carries info with positional relevance. For instance

your_rule([_,_,E|Rest], Accum, Result) :-
   Sum is Accum + E,
   your_rule(Rest, Sum, Result).
...

Solution 3

A prolog list is a classic list. Access is not direct. You have to iterate over to to find what you need.

You can get the nth element this way:

foo( [X1,X2,X3,X4,...,XN|Xs] ) :- ...

where [code]X[/code]n is the nth element of the list. Impractical for n larger than a small value. This is roughly analogous to a C/C++ pointer expression:

LLNode *nthElement = root->next->...->next ;

Otherwise, you have to iterate over the list to find the desired element, using a built-in predicate or a home-brew predicate, something like:

foo(Xs) :- nth_element(Xs,9,X) , ...

nth_element(Xs,N,X) :- nth_element(Xs,0,N,X) .

nth_element([X|Xs],N,N,X) :- !. nth_element([_|Xs],T,N,X) :- T1 is T+1 , nth_element(Xs,T1,N,X).

Share:
45,347

Related videos on Youtube

David Carpenter
Author by

David Carpenter

Updated on September 15, 2020

Comments

  • David Carpenter
    David Carpenter over 3 years

    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?

  • David Carpenter
    David Carpenter over 11 years
    so if make a rule that needs to unify something with certain element of a list passed in, how would I use this?
  • joel76
    joel76 over 11 years
    Here are examples of use ?- L = [a,b,c], nth0(Ind, L, a),nth0(2, L, X). L = [a,b,c], Ind = 0, X = c . or ?- L = [a,b,c], nth1(Ind, L, a), nth1(2, L, X). L = [a,b,c], Ind = 1, X = b .