2
$\begingroup$

Is there a way to use With as follows?

variables := {a = 2, b = 3};
With[variables, a^b]

Desired output

8

Obviously the above code will actually just output

With[variables, a^b]

I know I can do something similar to this by defining a list of rules and using the operator form of ReplaceAll, I just like the way the With syntax looks and would prefer to use it if possible.

$\endgroup$
  • $\begingroup$ Hmm… I don't think it's a good idea, once the variables is executed somewhere, a and b will be polluted. $\endgroup$ – xzczd Nov 8 '19 at 7:57
  • $\begingroup$ Related: (3864), (19758), (28610), (31708), (69590) $\endgroup$ – Mr.Wizard Nov 8 '19 at 8:46
  • 1
    $\begingroup$ @Mr.Wizard This question is exact duplicate of (204116). $\endgroup$ – Alexey Popkov Nov 8 '19 at 10:44
  • $\begingroup$ @Alexey do you think that one should be marked as a duplicate too? Is With/Block distinct enough to keep it separate from (24036)? $\endgroup$ – Mr.Wizard Nov 8 '19 at 13:01
  • $\begingroup$ @Mr.Wizard In principle, yes, it should be market as a duplicate too. $\endgroup$ – Alexey Popkov Nov 8 '19 at 15:00
4
$\begingroup$

A quick idiomatic approach is to do

Unevaluated[explicitExpression] /. OwnValues[variableWithSetDelayedDefinition]

You can find it in 76917 together with alternatives. See linked topics as well.

So here:

variables := {a = 2, b = 3};

With[variables, a^b] // Unevaluated // ReplaceAll @ OwnValues @ variables

8

| improve this answer | |
$\endgroup$
  • $\begingroup$ Linked topic or related ones do not seem to be close enough to be a duplicate but there is probably a duplicate somewhere. $\endgroup$ – Kuba Nov 8 '19 at 8:17
  • 1
    $\begingroup$ I reviewed the related questions and found a couple that I think work; let me know if you agree. Incidentally I reopened one of them, despite the fact that I was the one who closed it, because it really doesn't seem like a duplicate to me now. shrug $\endgroup$ – Mr.Wizard Nov 8 '19 at 9:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.