Back to Each-Right

Iterators · Each-Right · Practice Question

Find Sublists Containing Any of Several Values

Sign in to track your progress

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 numbers 2 or 0.

Expected result:

1 2 3 4
7 2 4 1
0 8
8 2 4

Solution

l where any each (2;0) in/: l

Alternative Solution

l where any each ((l=2) or (l=0))

Explanation

(2;0) in/: l

uses each-right (/:) to keep the left argument (2;0) fixed and test it against every sublist of l in turn. For each sublist, (2;0) in sublist returns two booleans — "does it contain 2?" and "does it contain 0?":

10b
10b
00b
01b
10b

any each then collapses each pair to a single boolean — "does this sublist contain 2 or 0 (or both)" — giving 11011b, and where picks out those sublists.

The alternative builds the same boolean column directly with = instead of in, comparing every sublist's values against 2 and against 0 atomically (since = is atomic, it threads through nested lists without needing an explicit iterator), then combining with or before reducing with any each.