Search code examples
prologiso-prolog

Union of two variable sets


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.


Solution

  • 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).