Iterators · Amend · Practice Question
Replace Even Values in a List of Lists with Zero
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)Replace all even values across all sublists of l with the value 0.
Expected result:
1 0 3 0
7 0 0 1
1 3 5 1 0
0 0
0 0 0Solution
@'[l;where each not l mod 2;:;0]Explanation
@ is amend — @[x;i;:;y] sets the items of x at indexes i to the value y, without rebuilding the rest of the list. Unlike , or #, amend modifies specific positions, which is exactly what's needed here: every sublist keeps its odd values untouched and only its even values overwritten.
where each not l mod 2computes, per sublist, the indexes of the even values (mod 2 is atomic so it threads through the nested list directly; where each then converts each sublist's boolean mask into a list of indexes).
@'[l; ...; :; 0]applies amend each-both (@') — pairing every sublist of l with its own list of even-value indexes, and setting those positions to 0 in that sublist. each-both is essential here because the index lists differ in both length and content from one sublist to the next; a plain @[l;...] (without ') would expect one shared index list for the whole of l.