简体   繁体   中英

How to check if two elements of nested lists are the same index in Prolog?

I want to create a predicate same_position(B,X,Y) that is true if element X and element Y have the same position within their respective nested lists.

For example,

same_position([[b,c,f],[a,d,g],[h,e]],c,d) would return true.

same_position(L,E1,E2):-
    position(L,E1,N),
    position(L,E2,N).

position(LL,E,N):-
    member(L,LL),
    nth0(N,L,E).

?- same_position([[b,c,f],[a,d,g],[h,e]],c,d).
true

?- same_position([[b,c,f],[a,d,g],[h,e]],b,N).
N = b ;
N = a ;
N = h ;
false.

So using the predicates from your other question this is pretty simple.

Here's my approach:

1. position predicate checks the positions of two elements.

2. It then compares the values.

position([H|T],Element1,Element2):-
    checkElement([H|T],Element1,P1),
    checkElement([H|T],Element2,P2),
    P1=P2.
checkElement([],_,_).
checkElement([H|T],Element,P):-
    (   member(Element,H)->
        nth0(P,H,Element);checkElement(T,Element,P)).

Example:-

?-position([[b,c,f],[a,d,g],[h,e]],b,g).
false
?-position([[b,c,f],[a,d,g],[h,e]],b,a).
true
false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM