Skip to content

GatherBy ​

Group elements by the value of a function, in order of first appearance.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageGatherBy✓
GatherBy(list, f)elements grouped by f(element)f(element), in first-appearance order.
Typed signatures
TypePackageApplies
(indexed_collection<T>, (T) any -> any) -> list<list<T>> where Tcombinatoricsalways

Domain: Collections

Details
  • Gather with the equivalence "same ff value" instead of plain equality.

Examples

Basic #

Grouped by residue mod 3

live ↗
InGatherBy([1,2,3,4,5,6,7],_1⁡↦_1⁡ mod 3)\mathrm{GatherBy}(\bigl\lbrack1, 2, 3, 4, 5, 6, 7\bigr\rbrack, \operatorname{\_1}↦\operatorname{\_1}\bmod3)Out[[1,4,7],[2,5],[3,6]]\bigl\lbrack\bigl\lbrack1, 4, 7\bigr\rbrack, \bigl\lbrack2, 5\bigr\rbrack, \bigl\lbrack3, 6\bigr\rbrack\bigr\rbrack

Grouped by absolute value

live ↗
InGatherBy([−2,1,2,−1,3],Abs)\mathrm{GatherBy}(\bigl\lbrack-2, 1, 2, -1, 3\bigr\rbrack, \mathrm{Abs})Out[[−2,2],[1,−1],[3]]\bigl\lbrack\bigl\lbrack-2, 2\bigr\rbrack, \bigl\lbrack1, -1\bigr\rbrack, \bigl\lbrack3\bigr\rbrack\bigr\rbrack

Groups by the value of a test, odds first because 11 appears first

live ↗
InGatherBy([1,2,3,4,5],IsOdd)\mathrm{GatherBy}(\bigl\lbrack1, 2, 3, 4, 5\bigr\rbrack, \mathrm{IsOdd})Out[[1,3,5],[2,4]]\bigl\lbrack\bigl\lbrack1, 3, 5\bigr\rbrack, \bigl\lbrack2, 4\bigr\rbrack\bigr\rbrack

Grouping by a key function: here the first element of each pair

live ↗
InGatherBy([[a,1],[b,1],[a,2],[d,1],[b,3]],First)\mathrm{GatherBy}(\bigl\lbrack\bigl\lbrack a, 1\bigr\rbrack, \bigl\lbrack b, 1\bigr\rbrack, \bigl\lbrack a, 2\bigr\rbrack, \bigl\lbrack d, 1\bigr\rbrack, \bigl\lbrack b, 3\bigr\rbrack\bigr\rbrack, \mathrm{First})Out[[[a,1],[a,2]],[[b,1],[b,3]],[[d,1]]]\bigl\lbrack\bigl\lbrack\bigl\lbrack a, 1\bigr\rbrack, \bigl\lbrack a, 2\bigr\rbrack\bigr\rbrack, \bigl\lbrack\bigl\lbrack b, 1\bigr\rbrack, \bigl\lbrack b, 3\bigr\rbrack\bigr\rbrack, \bigl\lbrack\bigl\lbrack d, 1\bigr\rbrack\bigr\rbrack\bigr\rbrack
Scope #

Pairs grouped by their last element

live ↗
InGatherBy([[a,1],[b,2],[c,1]],Last)\mathrm{GatherBy}(\bigl\lbrack\bigl\lbrack a, 1\bigr\rbrack, \bigl\lbrack b, 2\bigr\rbrack, \bigl\lbrack c, 1\bigr\rbrack\bigr\rbrack, \mathrm{Last})Out[[[a,1],[c,1]],[[b,2]]]\bigl\lbrack\bigl\lbrack\bigl\lbrack a, 1\bigr\rbrack, \bigl\lbrack c, 1\bigr\rbrack\bigr\rbrack, \bigl\lbrack\bigl\lbrack b, 2\bigr\rbrack\bigr\rbrack\bigr\rbrack
Applications #

Grouping by residue gives the classes mod 33 without writing an equivalence

live ↗
InGatherBy(1..10,_1⁡↦_1⁡ mod 3)\mathrm{GatherBy}(1..10, \operatorname{\_1}↦\operatorname{\_1}\bmod3)Out[[1,4,7,10],[2,5,8],[3,6,9]]\bigl\lbrack\bigl\lbrack1, 4, 7, 10\bigr\rbrack, \bigl\lbrack2, 5, 8\bigr\rbrack, \bigl\lbrack3, 6, 9\bigr\rbrack\bigr\rbrack
About
Examples6
Checked againstWolfram Language 6 agree
CrosswalkWolfram Language

See also: Gather, SplitBy, SortBy