How can I use functional code to achieve the same effect as the following procedural code
Do[
Do[
f[i,j],
{j,1,m}
],
{i,1,n}
]
Defining a function with some side-effect for demonstration purposes.
f[i_, j_] := Echo[{i, j}]
Here are some more WL-esque options:
Array[f, {2, 3}];
Outer[f, Range[2], Range[3], 1];
f @@@ Tuples[{Range[2], Range[3]}];
Note the ;
above to suppress the output. If your function indeed only has side-effects and you don't want the output (supposedly that's why you chose Do
instead of Table
), you can also use Scan
:
Scan[Echo, Tuples[{Range[2], Range[3]}]]
Do[f[i, j], {i, n}, {j, m}]
, which is almost as fast asArray
andOuter
(faster ifm*n
is very large) and quite a bit faster thanApple
orScan
. AndDo
uses very little memory. -- Now, my understanding is that in functional programming, one generally aims for functions to have no side effects, in which case,Null
seems the most efficient to accomplish the above. :) In other words, looking for functional code to accomplish a non-functional task seems odd. $\endgroup$Scan
might be useful in this setting. $\endgroup$