17
votes

Given two lists of variables, what is the most compact and canonical way in ISO Prolog to determine the union of both? That is, we want a definition for the (meta-logical) predicates

varset_union(VarSet1, VarSet2, Union)

and for a list of lists

varset_union(VarSets, Union)

where Union is a list of unique variables of the given VarSets.

Here is an overview of the built-ins in ISO/IEC 13211-1:1995 including Cor.2:2012.

2

2 Answers

13
votes

Solution using term_variables/2:

varset_union(VarSet1, VarSet2, Union):-
    term_variables([VarSet1|VarSet2], Union).

varset_union(VarSets, Union):-
    term_variables(VarSets, Union).

Solution using setof/3:

varset_union(VarSet1, Varset2, Union):-
    varset_union([VarSet1, VarSet2], Union).

varset_union([], []).
varset_union(VarSets, Union):-
    setof(Var, VarSet^(member(VarSet, VarSets), member(Var, VarSet)), Union).
2
votes

Based on Tudor's great answer, I have devised a definition of varset_union/3 that is more compact by 2 characters:

varset_union(VarSet1, VarSet2, Union):-
        term_variables(VarSet1+VarSet2, Union).

;-)