Iterators · Each · Practice Question
Sum Even Values in Each Sublist
Question
Given the following list of lists:
l:(1 2 3 4;7 2 4 1;1 3 5 1 8;0 8;8 2 4)Return the sum of all even values for each sublist of l.
Expected result:
6 6 8 8 14Solution
sum each l @' where each not l mod/: 2Explanation
This builds the result in stages, combining each, each-both, and each-right:
l mod/: 2computes the remainder of every value against 2, keeping the nested shape of l. (Each Right (/:) applies mod with the whole of l on the left to each item on the right — here just the single atom 2 — so this is the same as l mod 2: mod is atomic and already reaches inside nested lists.) not flips it so even values become 1b:
q)not l mod/: 2
0101b
0110b
00001b
11b
111bwhere each (...) applies where independently (each) to every sublist's boolean mask, returning the indexes of the even values per sublist.
l @' (...) uses each-both (') to index into each sublist of l with its own list of even-value indexes, picking out just the even values:
2 4
2 4
8
0 8
8 2 4Finally, sum each sums each of those sublists independently, giving the final result 6 6 8 8 14.
This question is a good illustration of how each, each-both, and each-right combine naturally in q — each handles "this sublist has its own index list", while each-right and each-both line up shapes that don't otherwise match.