Key

is a primitive monadic operator which takes a dyadic function operand where specified keys group the indices or major cells of an argument. It was introduced in Dyalog APL version 14.0 and is commonly compared to SQL's GROUP BY statement.

Description
Monadically, Key will group identical major cells together and applies the function operand once for each unique major cell. The function is applied with the unique major cell as left argument, while the right argument is the indices of major cells that match it:

In the dyadic case, Key applies the function to collections of major cells from the right argument corresponding to unique elements of the left argument:

The monadic case,  is equivalent to.

Vocabulary
A common problem with Key is the inability to control the order of the result (as Key will use the order of appearance) and the "vocabulary" (as Key will never include information for a major cell that doesn't occur). For example, here we want to count occurrences of the letters A, C, G, T: Since A is entirely missing in the argument, it isn't mentioned in the result either. Likewise, the result is mis-ordered due to G and T appearing before the first C. A common solution is to inject the vocabulary before the actual data, and then decrement from the counts: Now that the meaning of each count is known, the operand's left argument can be ignored, and the decrementing can be factored out from the operand:

Computing the unique
Key computes the set of unique major cells. Often, this collection is needed separately from the occurrence information, but can be hard to extract. For example, to get the most frequently occurring letter: Notice that 3 is the index in the unique set of letters, and so it is tempting to write: However, while this code works, it is inefficient in that the unique is computed twice. This can be avoided by letting Key return the unique and using that: Unfortunately, this can introduce a different inefficiency, in that the result of Key's operand can end up being a heterogeneous array (containing multiple datatypes), and these are stored as pointer arrays, consuming memory for one pointer per element, and forcing "pointer chasing" when addressing the data. A possible work-around is to collect the unique keys separately from the result of counts: If there are a large number of unique values, the repeated updating of the accumulating  variable can be an issue in itself.

Lessons

 * APL Cultivation

Documentation

 * Dyalog