I would like to be able to pass an unquoted string as a parameter to a Mathematica function [that I am writing] and have it show up without evaluation if the string happens to be defined. Thus I would like
Clear["Global`*"]
f[x_] := Print[ToString[x]];
f[Middle] (* prints the string Middle *)
Middle = 3
f[Middle] (* prints the string Middle *)
Obviously this cannot work the way I've written it. Yet it is legal to write
Plot[g[x],{x,0,3}, PlotStyle->Black]
and Black
happens to be a protected variable, so it will never be defined.
How can I emulate, or come close to emulating, this behavior. I'm willing to put up with some compromises in the function invocation syntax (in particular, the option syntax opt->Middle would be fine).
Apologies if this is somewhere in the docs. I couldn't find it...
Thanks.
Addendum: While J.M.'s solution answers the question I posed above, I would also like the following to work:
Clear["Global`*"]
SetAttributes[foo,HoldAll];
foo[x_] := Print[ToString[Unevaluated[x]]];
Table[foo[i],{i,{a,b,c}}] (* prints {i,i,i}, as expected *)
Table[foo[Evaluate[i]], {i,{a,b,c}}] (* prints {a,b,c} as expected *)
a = 3
Table[foo[Evaluate[i]], {i,{a,b,c}}] (* prints {3,b,c} *)
I would like the last line to print {a,b,c} just like the one before it - that is, I'd like i
evaluated only once. Am I asking too much?
For context: this is part of a larger function that computes something, but does so in different ways depending on the setting of a mode parameter. I want to be able to pass in that mode parameter without evaluation; hence the original question. But I also want to be able to invoke the function inside a Table function as above. Here's a simple example:
Clear["Global`*"]
SetAttributes[foo,HoldAll];
foo[x_] := Block[{z=ToString[Unevaluated[x]]}, If[x == "square", x^2, x+1]];
Table[Integrate[foo[Evaluate[i]],{x,0,3}],{i,{"square", "xyzzy"}}];
{9, 45/2}
a=3
Table[Integrate[foo[Evaluate[i]],{x,0,3}],{i,{"square", "xyzzy"}}];
{45/2, 45/2}
since in the second invocation the parameter to foo has the value 3, not the value a. How can I achieve both of these behaviors?