Several ways to do it. One compact solution would be:
fix_free_variables(Term) :-
term_variables(Term, Variables),
findall(1, member(1, Variables), Variables).
Example calls:
?- fix_free_variables([pair(key1,1), pair(key2,1), pair(key3,_G1), pair(key4,-_G1), pair(key5,- -_G1)]).
_G1 = 1.
?- fix_free_variables([pair(key1,1), pair(key2,1), pair(key3,_G1), pair(key4,-_G2), pair(key5,- -_G3)]).
_G1 = _G2, _G2 = _G3, _G3 = 1.
Both term_variables/2
and findall/3
are standard built-in predicates. member/2
is usually available either as a built-in predicate or as a library predicate.