# evaluate the bounds of iterator in the table given as a sequence?

We know that Table has the attribute of HoldAll therefore an input provided as follows will not evaluate:

Table[i^2, {i, Sequence[0, 5, 1]}]
(* Table::iterb: Iterator {i,Sequence[0,5,1]} does not have appropriate bounds. *)


Is there a way to devise a scheme to circumvent the problem?

• Table[i^2, {i, ##}] &[0, 5, 1]? – Szabolcs Sep 8 '17 at 23:24
• Why not just use Table[i^2, {i, Range[0, 5, 1]}]? – Carl Woll Sep 8 '17 at 23:38
• @Carl Woll this was a simple example. I needed to implement the other form at one occasion today. – Ali Hashmi Sep 8 '17 at 23:53
• @aardvark2012 - Table[i^2, Evaluate@{i, Sequence[0, 5, 1]}] – Bob Hanlon Sep 9 '17 at 4:26
• @BobHanlon The problem with this is that if i happens to have a global value before this call, it won't work. – Leonid Shifrin Sep 9 '17 at 14:05

I see no reason to ever try to evaluate something like:

Table[i^2, {i, Sequence[1, 5, 1]}]


Table[i^2, {i, Range[1, 5, 1]}]


For example:

foo = Sequence[1, 5, 1];
Table[i^2, {i, Range[foo]}]


{1, 4, 9, 16, 25}

If you must create a new function that allows a Sequence object, then the following is simpler:

SetAttributes[table, HoldAll]

table[a_, {b_, HoldPattern[Sequence[c__]]}] := Table[a, {b, Range[c]}]
table[a__] := Table[a]


(As @MichealE2 points out in the comments, one could have used {b, c} instead of {b, Range[c]} above, but I want to emphasize that using Range instead of Sequence is all that's needed, and that there is no real need to create a new table function).

Examples:

table[i^2, {i, Sequence[0, 5, 1]}]
table[i^2, {i, Sequence[3]}]
table[i^2, {i, 2}]


{0, 1, 4, 9, 16, 25}

{1, 4, 9}

{1, 4}

• You don't really need Range: table[a_, {b_, HoldPattern[Sequence[c__]]}] := Table[a, {b, c}] works for me. – Michael E2 Dec 8 '17 at 15:03
• +1 ! I was merely doing random experimentation with the language. – Ali Hashmi Dec 8 '17 at 22:18

I constructed a method to overcome the issue:

SetAttributes[table, HoldAllComplete];

table[body_, tail_] := Module[{p, q, sym = Unique["x"]},
{p, q} =
Map[(Hold[#] /. x_ /;(DeveloperHoldSymbolQ[x] && !MemberQ[Names["System*"],ToString[x]])
:> sym) &, {Unevaluated@body, Unevaluated@tail}];
Apply[Table, {p, q} /. {Hold[x_] :> x, Hold[x__] :> {x}}]
];

i = 10;
table[i^2, {i, Sequence[0, 5, 1]}]
(* {0, 1, 4, 9, 16, 25} *)

• @numbermaniac great ! You might want to add that as an answer. It never crossed my mind that it could be as simple. There are plenty of ways of doing things in MMA and I realize that not all approaches are efficient. Regardless, all approaches teach you a new way to look at the language – Ali Hashmi Dec 8 '17 at 4:41