listprologcartesian-productcross-product

Working with list of lists in Prolog


Please help me to solve this problem: I have a list of lists

[[1,2],[3,4]]

How do I get:

[1,3]

[1,4]

[2,3]

[2,4]

Or if I have a list of lists

[[1,2],[3,4],[6,7]]

How do I get:

[1,3,6]

[1,3,7]

[1,4,6]

[1,4,7]

[2,3,6]

[2,3,7]

[2,4,6]

[2,4,7]


Solution

  • You can do something like this:

    lists([], []).
    lists([[Head|_]|Lists], [Head|L]):-
      lists(Lists, L).
    lists([[_,Head|Tail]|Lists], L):-
      lists([[Head|Tail]|Lists], L).
    

    That is, take the first element of the first list in your input list and continue recursively with the remaining lists. As a second chance, skip that element and redo with the remaining elements.