wolfram-mathematica

How to store the first parameter of Block in a variable?


Let's say I have a function

MyFunc[x_] := x + y

I can do this:

Block[{y = 1}, MyFunc[1]]

which gives the result 2 correctly.

Now, what to do if I want to save {y = 1} into a variable, something like

var = {y = 1};
Block[var, MyFunc[1]]

This wouldn't work. I've experimented with different forms of Hold, but couldn't make it work.


Solution

  • y = 1;
    
    Block[{y = y}, MyFunc[1]]
    

    2

    Note the syntax colouring which indicates that the first y is local.

    enter image description here

    We can prove that the y passed into MyFunc[1] is the local y.

    enter image description here

    Passing in var as a list is tricky, but here is one way suitable for limited cases.

    var = HoldForm[{y = 1}];
    
    func = ToString[Hold[Block[var, MyFunc[1]]]];
    
    func = StringReplace[func, "var" -> ToString[var]];
    
    ReleaseHold[ToExpression[func]]
    

    2