4
$\begingroup$

The following code:

Table[i*j, Apply[Sequence , {{i, 1, 3}, {j, 1, 2}}]]

returns the error:

Table::nliter: Non-list iterator Sequence@@{{i,1,3},{j,1,2}} at position 2 does not evaluate to a real numeric value.

On the other hand, the following alternative (which should be completely equivalent) works fine:

Table[i*j, Sequence[{i, 1, 3}, {j, 1, 2}]]

My questions:

  • Why is the first version not working while the last one is?
  • How can I make the first line work in the simplest manner possible?

This is a subroutine I would need for a more complicated function.

$\endgroup$
1
  • 2
    $\begingroup$ MemberQ[Attributes[Table], HoldAll] gives True, so you need to do Table[i*j, Evaluate[Apply[Sequence, {{i, 1, 3}, {j, 1, 2}}]]]. $\endgroup$ Jul 15, 2022 at 15:40

2 Answers 2

4
$\begingroup$

Sequence is special. As mentioned in Details section of document of Sequence:

Sequence objects will automatically be flattened out in all functions except those with attribute SequenceHold or HoldAllComplete.

Indeed, HoldAll doesn't stop Sequence:

Hold[a, Sequence[b, c], d]
(* Hold[a, b, c, d] *)

The standard way to fix the first sample is, as mentioned by J.M. in the comment above, using Evaluate. Alternatively, you can:

With[{iter = Apply[Sequence, {{i, 1, 3}, {j, 1, 2}}]}, Table[i*j, iter]]

Table[i*j, ##] &@Apply[Sequence, {{i, 1, 3}, {j, 1, 2}}]

Related discussion can be found in Possible Issues section of document of Table BTW.

Finally, it's worth mentioning that, though Table owns HoldAll attribute, it doesn't mean it never evaluate its arguments. You may want to read the following post:

Unexpected behaviour from Table[]

$\endgroup$
2
$\begingroup$

An alternative:

ReleaseHold[HoldForm[Table][i*j, Apply[Sequence, {{i, 1, 3}, {j, 1, 2}}]]]
(*{{1, 2}, {2, 4}, {3, 6}}*)
$\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.