Search code examples
prolog

Unifying a list of goals in prolog


I have a list of goals that I would like to be unified at runtime such that I get a list of Variable, value pairs. How might I do this?

Example

db.pl:

alpha(a).
bravo(b).
bravo(c).
gs([alpha(X), bravo(Y)]).

Interpreter:

?- [db].
?- gs(L), solve(L, Out).
L = [alpha(X), bravo(Y)].
Out = [[[X, a], [Y, b]], [[X, a], [Y, c]]]

Solution

  • (I feel pretty bad for showing you this, I am very sure that you still misunderstood some point or another. In fact, it would be much better for you to study setof/3 and call/N. But, well what do we do for earning rep...)

    solve(L, Out) :-
       setof(Pairs, maplist(goal_pair,L,Pairs), Out).
    
    goal_pair(G, [V,W]) :-
       arg(1, G, V),
       setof(V, G, Vs),
       member(W, Vs).
    

    This will give you in SWI

    ?- gs(L), solve(L, Out).
       L = [alpha(_A),bravo(_B)], Out = [[[_A,a],[_B,b]],[[_A,a],[_B,c]]].
    

    There is no way to recover the variable names directly. You would have to parse the program yourself.