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$

Your Answer

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

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