@Kuba's approach works using up-values, which works very nicely for simple cases as the examples given in the question. However, it does not work if the want["..."]
expression is nested deeper inside a held expression, as noted in the comments.
Here is an approach using MakeExpression
that processes any expressions of the form want["..."]
before any evaluation happens:
MakeExpression[RowBox@{"Want", "[", str_, "]"}, StandardForm] :=
ToExpression[ToExpression@str, StandardForm, HoldComplete]
This works for all cases I can think of:
(* example in question *)
G[x_, y_] := Want["x^2+y^2"]
G[3, 4]
(* 25 *)
(* more deeply nested, as in comments to @Kuba's answer *)
G[x_, y_] := Want["x^2+y^2"] + 1
G[3, 4]
(* 26 *)
(* with the string stored in a variable *)
str = "x^2+y^2";
G[x_, y_] := Want[str] + 1
G[3, 4]
(* 26 *)
As noted by @Kuba in the comments, this of course only works if MakeExpression
is actually called. Notable exceptions where this is not the case are text-based front-ends and package files imported via Get
.