listprolog

Iterate through two lists at same index


How can you iterate through two lists with the same index, so that you get a pair of each list:

?- X = [1, 2, 3], Y = [a, b, c], ...
ElemX = 1,
ElemY = a;

ElemX = 2,
ElemY = b;

ElemX = 3,
ElemY = c.

Solution

  • Loop through both lists simultaneously:

    member2(E1, [H1|T1], E2, [H2|T2]) :-
        member2_(T1, T2, H1, H2, E1, E2).
    
    member2_(_, _, E1, E2, E1, E2).
    member2_([H1|T1], [H2|T2], _, _, E1, E2) :-
        member2_(T1, T2, H1, H2, E1, E2).
    

    Result in swi-prolog:

    ?- member2(E1, [1, 2, 3], E2, [a, b, c]).
    E1 = 1,
    E2 = a ;
    E1 = 2,
    E2 = b ;
    E1 = 3,
    E2 = c.