Consider the following function definition:
ForEach[iterators__] := Table[#, iterators] &;
Two questions about it:
I. It works perfectly if you call it like ForEach[{m,3},{n,3}]@{m,n}
and outputs:
$$ \left( \begin{array}{ccc} \{1,1\} & \{1,2\} & \{1,3\} \\ \{2,1\} & \{2,2\} & \{2,3\} \\ \{3,1\} & \{3,2\} & \{3,3\} \end{array} \right) $$
However, the result of ForEach[{m, 3}, {n, 3}]@ToString[m n]
is:
$$ \left( \begin{array}{ccc} \text{m n} & \text{m n} & \text{m n} \\ \text{m n} & \text{m n} & \text{m n} \\ \text{m n} & \text{m n} & \text{m n} \end{array} \right) $$
Why it doesn't treat m
and n
as known variables?
II. How can I pass a piece of code to the function to be run before each iteration? For instance, I want to call the function with an option like k=0; ForEach[{m, 3}, {n, 3},Pre->k++]@{k,m,n}
which is the same as k = 0; Table[k++; {k, m, n}, {m, 3}, {n, 3}]
?