2
$\begingroup$

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}
   ]
$\endgroup$
2
  • 2
    $\begingroup$ There's the unnested Do[f[i, j], {i, n}, {j, m}], which is almost as fast as Array and Outer (faster if m*n is very large) and quite a bit faster than Apple or Scan. And Do 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$
    – Michael E2
    Commented Apr 16, 2022 at 22:49
  • $\begingroup$ Scan might be useful in this setting. $\endgroup$ Commented Apr 17, 2022 at 0:53

1 Answer 1

9
$\begingroup$

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]}]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.