1
$\begingroup$

I want to be able to define a set of iterators for nested Do loops, such as

asdf = {i[#], {-1, 1}} & /@ Range[2, 8]
num = 0;
Do[num++; Print[num];, ##] &[asdf]

or

Do[num++; Print[num];, Sequence@@asdf]

The iteration variables are i[1]...i[8]. The problem is that Do automatically encloses the arguments in an extra { } which I can't seem to get around.

$\endgroup$

closed as off-topic by xzczd, MarcoB, Edmund, LCarvalho, Vitaliy Kaurov Feb 28 at 0:35

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – xzczd, MarcoB, Edmund, LCarvalho, Vitaliy Kaurov
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    $\begingroup$ 1. Do[num++; Print[num];, ##] & @@ asdf 2. Do[num++; Print[num];, Sequence @@ asdf // Evaluate] $\endgroup$ – xzczd Feb 17 at 7:56
3
$\begingroup$

Perhaps this will work for you.

num = 0;
With[{indxs = Sequence @@ ({i[#], -1, 1} & /@ Range[2, 8])},
  Do[num++; Print[num], indxs]]

Caution: evaluating the above code creates 2187 print cells.

In the case where it is important for you to store the iterator specification in a variable, you could write

num = 0;
indxs = Sequence @@ ({i[#], -1, 1} & /@ Range[2, 3]); 
Do[num++; Print[num], Evaluate @ indxs]
$\endgroup$
  • $\begingroup$ Thanks, so I think I understand that the issue has to do with the Do iterator having the Hold attribute, so why does using With not require the use of Evaluate? $\endgroup$ – Kai Feb 19 at 0:56
  • $\begingroup$ @Kai. Because the first argument of With is evaluated and substituted into the Do expression before the argument evaluation of the Do expression itself, With is somewhat like the macro preprocessor of C/C++ in terms its place in the evaluation chain. $\endgroup$ – m_goldberg Feb 19 at 1:24

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