7
$\begingroup$

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.

$\endgroup$

1 Answer 1

6
$\begingroup$

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]
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.