Iterators · Each-Left · Practice Question
Append a Value to Every 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)Join the number 9 to the end of each sublist.
Expected result:
1 2 3 4 9
7 2 4 1 9
1 3 5 1 8 9
0 8 9
8 2 4 9Solution
l,\:9Alternative Solution
l,'9Alternative Solution
@[l;(::);,;9]Explanation
The each-left iterator:
\:pairs the fixed right argument 9 against every sublist of l in turn, joining it to the end of each one independently.
Because 9 is a single atom rather than a list, each-both (,') produces the same result here — with an atomic right argument there's nothing for ' to line up against per item, so it behaves the same as \:. This stops being true the moment the right argument is itself a list with one value per sublist.
The amend form, @[l;(::);,;9], takes a different route: the index (::) selects every item of l, and amend applies , with 9 to each selected item, giving the same result. It is useful to know because it generalises to amending only some sublists — for example @[l;0 2;,;9] appends 9 to the first and third sublists only.