1

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.

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.