Mathematica Asked on May 23, 2021
For reusable code it’s good practice to use Module[]
to localize iteration variables used by Table[]
, as explained by this post.
Is it possible to use some Hold / ReleaseHold gymnastics to write a function ModuleTable[]
which behaves like this?
ModuleTable[f[i], {i, 1, 10}]
gets automatically expanded into
Module[{i}, Table[f[i], {i, 1, 10}]]
Here is one way to do this for arbitrary number of iterators:
ClearAll[ModuleTable]
SetAttributes[ModuleTable, HoldAll];
ModuleTable[code_, iters__List] :=
Replace[
DeleteCases[Hold[iters][[All, 1]], Except[_Symbol]],
Hold[vars__] :> Module[{vars}, Table[code, iters]]
]
where DeleteCases
was necessary since iterators may not include a symbol. The main device to control code evaluation, used here, is called injector pattern on this site (you can search for this term to see other examples of its use).
For example:
ClearAll[a, b]
a = 1;
b = 2;
ModuleTable[a + b, {a, 1, 3}, {2}, {b, 2, 5}]
(* {{{3, 4, 5, 6}, {3, 4, 5, 6}}, {{4, 5, 6, 7}, {4, 5, 6, 7}}, {{5, 6, 7, 8}, {5, 6, 7, 8}}} *)
Correct answer by Leonid Shifrin on May 23, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP