Iterators · Amend · Practice Question
Replace a Single Element in a Matrix
Question
Given:
l:4 cut til 160 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15Replace the number 11 with the number 40.
Expected result:
0 1 2 3
4 5 6 7
8 9 10 40
12 13 14 15Solution
.[l;(2;3);:;40]Explanation
. is amend applied with a path of indexes rather than a single one — .[x;(i;j);:;y] drills down into x at row i, column j, and sets that one value to y, leaving everything else in the matrix untouched.
Here (2;3) addresses row 2 (8 9 10 11), position 3 within that row (the value 11), and replaces it with 40. This is the natural extension of @[x;i;:;y] to nested structures: @ amends a single level of a list, while . follows a path through multiple levels — exactly what's needed to reach into one cell of a matrix without rebuilding the whole thing.