Iterators · Each-Right · Practice Question
Find Sublists Containing a Value
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)Write a q expression that returns all sublists which contain the number 2.
Expected result:
1 2 3 4
7 2 4 1
8 2 4Solution
l where 2 in/: lExplanation
The each-right iterator:
/:pairs a single left argument against every item on the right, one at a time. Here the fixed left argument 2 is tested with in against every sublist of l independently:
q)2 in/: l
11001bproducing one boolean result per sublist — 1b wherever that sublist contains 2. where then keeps only the sublists for which this is true.
each-right is the mirror image of each-left: instead of a fixed right argument paired against every item on the left, it's a fixed left argument paired against every item on the right.