What I want is an f
that will work like this:
x = 1;
myOut = f[x]; (* it should return {x -> 2} , the 2 is the new data *)
x /.myOut (* execute this line if I want to overwrite the current x;
or I can leave my old x as is but still have the new data
in myOut *)
The main challenge for me now is to:
print the rule to a variable, while this variable is already assigned a value, say, x = 1
.
In the module I have to avoid using its name x
because it will automatically get substituted by 1 (in this example above). The variable name should be provided by the user so that its name is unknown and I cannot hard-code it in my module.
So far, I can fetch the input variable name x
no problem. I can also overwrite x
inside the module without explicitly using its name. I'm stuck at printing it in a rule.
Using HoldForm[ ]
creates a tiny white space that ruins the rule (while avoiding being detected as not a rule when executed!), and neither does Defer[ ]
work in a mysterious way (to me).
Below is this failed attempt with the tiny white space:
myFunc[inVar_] := Module[{newData,},
newData = 1 + inVar; (* just some computation *)
Print[ HoldForm[ inVar ] -> newData ];
(* Besides Print[ ], I also tried Return[], List[], or just the rule (expression) itself; the outcome are all the same *)
]; (* End of Module *)
For example, myOut = myFunc[x]
will print x->2
with a tiny white space right after the x
and before the arrow. It kind of looks like x,->2
where the comma represents the white space.
The usual x/.myOut
will not work because of this. I've tried it, if I manually remove that tiny space then the rule will work.
Besides HoldForm[ ]
, using a string for the variable name creates double quotes.
Inactive[ ]
, Unevaluated[ ]
, With[ ]
don't work either, at least the ways I've tried.
I'm currently working on MakeExpressions[ ]
and boxes, but I haven't made much progress and am wondering if I'm on the right track.
Thank you very much.
-------- a little info hopefully for more efficient discussions ----
Thanks to the many answers to other questions provided by Kuba, Mr.Wizard and Leonid, just to name a few, I have learned how to:
(a) obtain the variable name provided by the user and append sequential index or strings etc to make use of it,
(b) inject stuff into held expressions, one of the coolest thing I've ever seen with /._[x__] ->
(c) forcefully assign values to existing variables without explicitly using its name, like so.
As a whole I consider myself a beginner, knowing basic syntax and some isolated tricks only.
x/.x->f[x]
. You don't need any module for that. $\endgroup$f[x0_] := HoldPattern[x] -> 2
? You can't simply havex -> 2
ifx
has been assigned a value (e.g.,x = 1
). Or possiblyClearAll[f]; SetAttributes[f, HoldAll]; f[var_] := Module[{newData}, <code to calculate newData >; HoldPattern[var] -> newData]
. $\endgroup$