Iterators · Each · Practice Question
Count Occurrences as a Dictionary
Question
Given the following list:
l:`a`a`a`a`a`a`b`c`c`d`e`e`e`eCount the number of occurrences of each element in l. Return the result as a dictionary.
Expected result:
a| 6
b| 1
c| 2
d| 1
e| 4Solution
count each group lAlternative Solution
(distinct l)!sum each (distinct l)=\:lAlternative Solution
exec count i by l from ([] l)Explanation
group l returns a dictionary mapping each distinct value to the list of indexes where it occurs:
q)group l
a| 0 1 2 3 4 5
b| ,6
c| 7 8
d| ,9
e| 10 11 12 13Applying the each iterator:
'to count runs count independently against every value of that dictionary, turning each list of indexes into its length — giving the occurrence count per key, while keeping the original keys untouched.
The first alternative builds the same result manually: (distinct l)=\:l pairs each distinct value against the whole list using each-left, producing one boolean mask per distinct value, and sum each counts the 1s in each mask.
The second alternative uses qSQL's by clause to group and count directly.