Function Repository Resource:

MultisetSum

Source Notebook

Perform the sum operation on multisets

Contributed by: Robert B. Nachbar (Wolfram Solutions)

ResourceFunction["MultisetSum"][list1,list2,]

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

ResourceFunction["MultisetSum"][list]

effectively sorts the elements of list.

ResourceFunction["MultisetSum"][assoc1,assoc2,]

gives an Association where the keys are the union of the keys in the associations associ and the values are the sum of the merged values.

Details and Options

If the listi are considered as multisets, ResourceFunction["MultisetSum"] gives their sum.
The listi must have the same head, but it need not be List.
The values of associ must be counts—that is, non-negative Integer values.

Examples

Basic Examples (2) 

Give a sorted list of elements from all the lists:

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

Multisets as an Association of counts:

In[2]:=
ResourceFunction[
 "MultisetSum"][<|"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 (1) 

MultisetSum works with any head, not just List:

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

Properties and Relations (1) 

Compare to Union:

In[4]:=
ResourceFunction[
 "MultisetSum"][{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]=

Publisher

Robert Nachbar

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 19 February 2019

Related Resources

License Information