Wolfram Research

Function Repository Resource:

MultisetUnion

Source Notebook

Perform the union operation on multisets

Contributed by: Robert B. Nachbar (Wolfram Solutions)

ResourceFunction["MultisetUnion"][list1,list2,]

gives a sorted list of all the elements that appear in any of the listi. The number of occurances of each distinct element is the maximum of the counts in each of the listi.

ResourceFunction["MultisetUnion"][list]

effectively sorts the elements of list.

Details and Options

If the listi are considered as multisets, MultisetUnion gives their union.
The listi must have the same head, but it need not be List.

Examples

Basic Examples

Give a sorted list of elements from all the lists:

In[1]:=
ResourceFunction[
 "MultisetUnion"][{a, b, a, c}, {d, a, e, b}, {c, d, a, d}]
Out[1]=

Multisets as Association of counts :

In[2]:=
ResourceFunction[
 "MultisetUnion"][<|"a" -> 3, "b" -> 1, "c" -> 2, "d" -> 1|>,
 <|"a" -> 2, "b" -> 2, "c" -> 2, "e" -> 1|>,
 <|"a" -> 1, "b" -> 2, "c" -> 2, "e" -> 2|>]
Out[2]=

Scope

MultisetUnion works with any head, not just List :

In[3]:=
ResourceFunction["MultisetUnion"][f[a, b], f[c, a], f[b, b, a]]
Out[3]=

Properties and Relations

Compare to Union:

In[4]:=
ResourceFunction[
 "MultisetUnion"][{a, b, a, c}, {d, a, e, b}, {c, d, a, d}]
Out[4]=
In[5]:=
Union[{a, b, a, c}, {d, a, e, b}, {c, d, a, d}]
Out[5]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

See Also

License Information