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 VarSet
s.
Here is an overview of the built-ins in ISO/IEC 13211-1:1995 including Cor.2:2012.
ii) Union of two sets:= n(A) + n(B) – n(A ∩ B) Simply, the number of elements in the union of set A and B is equal to the sum of cardinal numbers of the sets A and B, minus that of their intersection.
The symbol ∪ is employed to denote the union of two sets. Thus, the set A ∪ B—read “A union B” or “the union of A and B”—is defined as the set that consists of all elements belonging to either set A or set B (or both).
Is A ∩ B Equal to B ∩ A? As per the commutative property of the intersection of sets, the order of the operating sets does not affect the resultant set and thus A ∩ B equals B ∩ A.
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).
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).
;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With