librarylibs/Grouping/src/Grouping.xtl
Grouping: grouping by key -- the groups, and counts, sums, means, least and greatest per key, or any function per key. Import it with an alias of your choice: "gr:" u_se< "Grouping". Put libs/Grouping/src on XETAL_PATH ("just path"); the reference is libs/Grouping/docs. Names with l: are exported; those under h: are private to this file.
Keys and values are lists of one length: item i of the values belongs to key i. Keys may be numbers, characters or texts (boxes). Every result has one item per distinct key, in the order of u_nique keys (first seen first), as APL's key operator gives them.
Grouping
ˡg̲roups : Eq a => a -> b -> Box b
keys g_roups values: the values of each key, a list per key.
ˡg̲roups ← { k v → '{ u → (k = u) r̲eplicate v } m̲ap u̲nique k }
ˡb̲y : Eq c => (a -> b) -> c -> a -> b
keys 'f b_y values: f applied to each key's values (f gives one number per group): keys '{ '+ r_/ _r } gr:b_y values.
ˡb̲y ← { f̲ k v → '{ u → f̲ (k = u) r̲eplicate v } e̲ach u̲nique k }
Per-key summaries
ˡc̲ount : Eq a => a -> Int
gr:c_ount keys: how many items each key has.
ˡc̲ount ← { k → '{ u → t̲ally w̲here k = u } e̲ach u̲nique k }
ˡs̲um : (Eq a, Num b) => a -> b -> b
keys s_um values, keys m_ean values: per key.
ˡs̲um ← { k v → k '{ '+ r̲/ ⍵ } ˡb̲y v }
ˡm̲ean : (Eq a, Num b) => a -> b -> Float
ˡm̲ean ← { k v → (f̲loat k ˡs̲um v) ÷ f̲loat ˡc̲ount k }
ˡl̲east : (Eq a, Num b) => a -> b -> b
keys l_east values, keys g_reatest values: per key.
ˡl̲east ← { k v → k '{ 'm̲in r̲/ ⍵ } ˡb̲y v }
ˡg̲reatest : (Eq a, Num b) => a -> b -> b
ˡg̲reatest ← { k v → k '{ 'm̲ax r̲/ ⍵ } ˡb̲y v }