2
$\begingroup$

I have defined a function like this:

f[q_] := Module[{g},
    g[x_] := Evaluate[q];
    ...
]

I am calling the function like this:

f[2+4x+6x^2]

It's not working, because when I look at the definition of g in f, it looks like this:

f$23750[x$_]:=2+4 x+6 x^2

The "$" makes it appear like it's trying to treat x as local to the module, but I need to to retain it as exactly x so I can pass in an equation in x. I don't want to pass a lambda as this is more cumbersome and hard to read. What am I doing wrong?

$\endgroup$
3
$\begingroup$

You're running into the automatic renaming of variables that Mathematica does when there are variable naming conflicts. One workaround is to use Inactive/Activate as follows:

f[q_] := Module[{g},
    Activate[Inactive[SetDelayed][g[x_],Evaluate[q]]];
    DownValues[g]
]

Then:

f[2 + 4 x + 6 x^2]

{HoldPattern[g$411457[x_]] :> 2 + 4 x + 6 x^2}

shows that the variable renaming has been avoided.

$\endgroup$
0
$\begingroup$

I think you want something like this:

f[q_]:= Module[{g},
  g[x_]:= Evaluate[q];
  g[q]]

Your original code does not evaluate your function g[].

$\endgroup$
3
  • $\begingroup$ It does evaluate it later (in the "..." part, which I was omitting for brevity). And when I pass an integer to g, it returns my equation, not the result of substituting the integer into the equation. When I passed g to "Definition" it appeared to show me that it wasn't using "x" but was instead changing it to "x$". $\endgroup$
    – Michael
    Sep 28 '19 at 22:20
  • $\begingroup$ Incidentally, if I change the equation I pass to substitute "x" with "x$" it works, but this seems like a workaround in misunderstanding of the correct way to define g. $\endgroup$
    – Michael
    Sep 28 '19 at 22:21
  • $\begingroup$ @Michael - I suggest that you edit your question and supply the minimum workable code that demonstrates the problem. $\endgroup$
    – Jagra
    Oct 2 '19 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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