Create local alias for variable

7

1

I have a function whose parameters are passed "by reference"

Clear[foo]
SetAttributes[foo, HoldFirst]
foo[t_] := t = 10

Is it possible to create an alias for t within foo, so inside the function I can call it something else? I'm looking for something like

foo[t_] := With[{k = t}, k = 10]

But instead of With I want something that keeps t unevaluated until inside the function body.

arax

Posted 2018-05-09T00:42:25.253

Reputation: 1 781

Answers

6

Undocumented but very useful, it is exactly what With[{ k := t }, ...] will do:

Clear[foo]
SetAttributes[foo, HoldFirst]
foo[t_] := With[{k := t}, k++ ]

a=5;
foo[a];
a

6

I use it a lot, read more in:

What are some useful, undocumented Mathematica functions? / a / 121173 / Delayed With, Block, and Module

A more documented approach:

ClearAll[foo]
SetAttributes[foo, HoldFirst]
foo[t_] := Module[{k}, Unevaluated[k++] /. k :> t]

Kuba

Posted 2018-05-09T00:42:25.253

Reputation: 129 207