Tally¶
Status: Stable
documented, exercised by the test suite and/or worked examples, with no known limitations recorded.
Description¶
Tally[list] counts the number of occurrences of each distinct element in list.
Examples (5)¶
Every input below was run against the current Mathilda build and its output recorded.
Basic examples (2)¶
In[1]:= Tally[<|"a" -> 1, "b" -> 1, "c" -> 2|>]
Out[1]= {{1, 2}, {2, 1}}
In[2]:= Commonest[<|"a" -> 1, "b" -> 1, "c" -> 2|>]
Out[2]= {1}
Applications (3)¶
In[3]:= Tally[{a, b, a, c, b, a}]
Out[3]= {{a, 3}, {b, 2}, {c, 1}}
In[4]:= Tally[Table[Mod[n^2, 5], {n, 0, 20}]]
Out[4]= {{0, 5}, {1, 8}, {4, 8}}
In[5]:= Tally[Table[GCD[n, 12], {n, 1, 12}]]
Out[5]= {{1, 4}, {2, 2}, {3, 2}, {4, 2}, {6, 1}, {12, 1}}
Implementation notes¶
Algorithm. builtin_tally counts distinct elements, returning {element, multiplicity}
pairs in first-occurrence order. With the default sameness test it uses a chained hash table
(expr_hash for bucketing, expr_eq for equality) for O(n) expected counting; with a custom
two-argument test it falls back to an O(n²) linear scan, evaluating test[a, b] per
comparison. Multiplicities are tracked in a parallel int64_t array.
Attributes: Protected.
References¶
See also: Commonest, Counts, CountsBy
- Source:
src/list.c - Specification:
docs/spec/builtins/data-structures.md - Tests:
tests/test_association.c - Tests:
tests/test_packed_list.c
Notes & additional examples¶
Notes¶
Tally[list] returns {element, count} pairs for each distinct element, in the
order of first appearance. It is a compact way to read off the distribution of a
computed sequence — for example, the multiplicities of the quadratic residues
mod 5 ({0, 1, 4} appearing 5, 8, and 8 times among n = 0 .. 20), or the
divisor structure of GCD[n, 12].