sourcelibs/Grouping/src/Grouping.xtl

1⍝│ Grouping: grouping by key -- the groups, and counts, sums, means, 2⍝│ least and greatest per key, or any function per key. 3⍝│ Import it with an alias of your choice: "gr:" u_se< "Grouping". 4⍝│ Put libs/Grouping/src on XETAL_PATH ("just path"); the reference is libs/Grouping/docs. 5⍝│ Names with l: are exported; those under h: are private to this file. 6⍝│ 7⍝│ Keys and values are lists of one length: item i of the values 8⍝│ belongs to key i. Keys may be numbers, characters or texts (boxes). 9⍝│ Every result has one item per distinct key, in the order of 10⍝│ u_nique keys (first seen first), as APL's key operator gives them. 11 12⍝━━ Grouping 13 14⍝│ keys g_roups values: the values of each key, a list per key. 15ˡg̲roups ← { k v → '{ u → (k = u) r̲eplicate v } m̲ap u̲nique k } 16 17⍝│ keys 'f b_y values: f applied to each key's values (f gives one 18⍝│ number per group): keys '{ '+ r_/ _r } gr:b_y values. 19ˡb̲y ← { f̲ k v → '{ u → f̲ (k = u) r̲eplicate v } e̲ach u̲nique k } 20 21⍝━━ Per-key summaries 22 23⍝│ gr:c_ount keys: how many items each key has. 24ˡc̲ount ← { k → '{ u → t̲ally w̲here k = u } e̲ach u̲nique k } 25 26⍝│ keys s_um values, keys m_ean values: per key. 27ˡs̲um ← { k v → k '{ '+ r̲/ ⍵ } ˡb̲y v } 28ˡm̲ean ← { k v → (f̲loat k ˡs̲um v) ÷ f̲loat ˡc̲ount k } 29 30⍝│ keys l_east values, keys g_reatest values: per key. 31ˡl̲east ← { k v → k '{ 'm̲in r̲/ ⍵ } ˡb̲y v } 32ˡg̲reatest ← { k v → k '{ 'm̲ax r̲/ ⍵ } ˡb̲y v }