Is is possible to assign {x = 2, y = 3, z = 4}
to a variable var
so that one can write
Block[var, x*y*z]
(or similar) instead of
Block[{x = 2, y = 3, z = 4}, x*y*z]
?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityIs is possible to assign {x = 2, y = 3, z = 4}
to a variable var
so that one can write
Block[var, x*y*z]
(or similar) instead of
Block[{x = 2, y = 3, z = 4}, x*y*z]
?
This could be another case for the injector pattern:
var = Hold@{x = 2, y = 3, z = 4}
var /. Hold[inj_] :> Block[inj, x*y*z]
(*24*)
?x
(*Global`x --- so we did not leak*)
Here's something I found:
With[{h := {x = 7, y = 8}},
Block[h, x y]]
56
Sequence
); in cases where it does it's surely easier to read for those not already acquainted with the "injector" or deeply familiar with replacement rules. +1
$\endgroup$
– Mr.Wizard
Apr 26 '13 at 2:07
var
but the Set
expressions explicitly. Nevertheless it is instructive and my +1 stands.
$\endgroup$
– Mr.Wizard
Apr 26 '13 at 2:17
var /: Block[var, code_] := Block[{x = 2, y = 3, z = 4}, code]
So
x = 100;
Block[var, x + 2]
(* 4 *)
The way I prefer is
var := {x = 2, y = 3, z = 4}
ReleaseHold[Hold[Block[var, x*y*z]] /. OwnValues[var]]
x
-> 24
-> x
Or
Apply[Block, Hold[var, x*y*z] /. OwnValues[var]]
x
-> 24
-> x
For
hVars = Hold[{x = 2, y = 3, z = 4}];
We can do
ReleaseHold[Hold[Block][hVars, Hold[x*y*z]]]
x
-> 24
-> x