Search code examples
listprologtuplesprolog-findall

How to inline a goal with findall/3, (use just one predicate)?


I have a knowledgebase that looks something like this

fact1(1, _, a, _, _).
fact1(2, _, c, _, _).
fact1(3, _, d, _, _).
fact1(4, _, f, _, _).

fact2(_, 1, b, _, _).
fact2(_, 2, c, _, _).
fact2(_, 4, e, _, _).

For every fact1 & fact2, where (in this example) the numbers match up, I want to have a list of the corresponding letters as tuples. I would like to use findall/3 and only one predicate for this.

I have asked a question here before on how to solve something similar, where the answer was using two predicates. That solution looked like this:

find_item((Val1,Val2)):-
    fact1(A, _, Val1, _, _),
    fact2(_, A, Val2, _, _).`

test(Items) :-
    findall(Item,find_item(Item),Items).

The result for the given example of facts, should look like this:

[(a, b),  (c, c),  (f, e)]

Can the two predicates be combined using just findall/3?


Solution

  • You can inline procedure find_item/1 as the goal of findall/3 (use a conjunction of goals instead of a single goal):

    test(Items):-
      findall((Val1, Val2), (fact1(A, _, Val1, _, _), fact2(_, A, Val2, _, _)), Items).