0
$\begingroup$

Sometimes I'd like to make a function, which would take an argument "by reference" instead of usual "by value". This is semantically similar to what e.g. AppendTo does: changes the variable passed to it. But when I try to do this straightforwardly, I get:

myFunc[x_] := (Clear[x]; x = 1)
test = 0; (* dirty the variable *)
myFunc[test];

Clear::ssym: 0 is not a symbol or a string. >>

Set::setraw: Cannot assign to raw object 0. >>

So, seems x is treated as "the value of x" inside the function. How do I change myFunc to treat x as "the symbol passed as x", so that it works like intended?

$\endgroup$
  • $\begingroup$ Also specifically addressed here: (18737) $\endgroup$ – Mr.Wizard Jan 28 '15 at 6:40
  • $\begingroup$ I think a better way to do this is to make a local variable in the module, assign that the value of the input, then make modification on the local variable, and return that at the end. This is in the spirit of how Mathematica programming is done. $\endgroup$ – Nasser Jan 28 '15 at 7:44
  • $\begingroup$ @Nasser of course, it was how I used to work around this. But Pickett's answer lets me do it more conveniently in some cases. $\endgroup$ – Ruslan Jan 28 '15 at 8:22
  • $\begingroup$ @Ruslan Could I ask why you want to assign a value to x (or its 'value' test) inside your function? I'm not saying you don't have good reason but to an external observer it just seems an odd thing to want to do. $\endgroup$ – Ymareth Jan 28 '15 at 9:13
  • $\begingroup$ @Ymareth the function may take multiple arguments to change, and not having to say {a,b,c}=f[a,b,c] is really convenient. After all, even the built-in AppendTo[v,val] is also nothing more than syntactic sugar over v=Append[v,val], but it's so useful. This can be compared to using x+=y instead of x=x+y. $\endgroup$ – Ruslan Jan 28 '15 at 9:37
2
$\begingroup$

You give the function the HoldFirst or HoldAll attribute:

myFunc[x_] := (Clear[x]; x = 1)
SetAttributes[myFunc, HoldFirst]
test = 0;
myFunc[test];
test

1

$\endgroup$

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