1
$\begingroup$

What I'm doing wrong? 1st function works as expected but the 2nd one doesn't. What I want is to enter an algebraic expression and two numeric constants and get the same result as with the first function. Thanks in advance.

f[u_, v_] := Module[{g}, g[x_] := 3 x - 2; g[u] + g[v]]
f[2, 3]
(* 11 *)

h[m_, u_, v_] := Module[{g}, g[x_] := m; g[u] + g[v]]
h[3 x - 2, 2, 3]
(* -4 + 6 x *)
$\endgroup$
1
  • $\begingroup$ Some form of this question comes up a lot. It's one of the more confusing aspects of the language. I have marked your question as "already has an answer" pointing to three existing Q&A's that I believe you will find useful. $\endgroup$
    – Mr.Wizard
    Aug 25, 2018 at 15:56

3 Answers 3

1
$\begingroup$
ClearAll[h1]
h1[m_, u_, v_] := Module[{g},
   g[y_] := Block[{x = y}, m]; 
   g[u] + g[v]]
h1[3 x - 2, 2, 3]

11

Alternatively,

ClearAll[h2]
h2[m_, u_, v_] := Module[{g},
   g[y_] := m /. First[Cases[m, _Symbol, Infinity]] -> y; 
   g[u] + g[v]]
h2[3 x - 2, 2, 3]

11

h2[3 foo - 2, 2, 3]

11

$\endgroup$
1
$\begingroup$

Change your approach: pass the function.

h2[g_, u_, v_] := g[u] + g[v]
h2[x \[Function] 3 x - 2, 2, 3]

If you are stuck with the expression, you can still do this:

xpr = 3 x - 2;
h2[x \[Function] Evaluate@xpr, 2, 3]
$\endgroup$
1
$\begingroup$

Updated to fix my first answer

(I had some lingering definitions that misled me to thinking my first answer worked. Here's an update that should work)

I think it would be better to include the independent variable explicitly in your function. For example:

h[m_, x_, u_, v_] := With[{g = Function[x, m]}, g[u]+g[v]]

(The above definition gets a benign syntax warning about repeated symbols in a nested scoping construct. If this bothers you, you can use the equivalent alternative):

h[m_, x_, u_, v_] := With[{g = Function @@ Hold[x, m]}, g[u] + g[v]]

Then:

h[3x - 2, x, 2, 3]

11

On the other hand, we can repair your method by using Activate and Inactive to get around the lexical renaming that happens with SetDelayed:

h[m_, u_, v_] := Module[{g},
    Activate @ Inactive[SetDelayed][g[x_],m];
    g[u]+g[v]
]

Then:

h[3x - 2, 2, 3]

11

$\endgroup$
2
  • $\begingroup$ @Sanmuten What is not working? $\endgroup$
    – Carl Woll
    Aug 24, 2018 at 20:31
  • $\begingroup$ 1st example works but Mathematica issues a warning highlighting "x" variable in red. It reads as follows “ 'x' occurs twice in a nested scoping construct, in a way that is likely to be an error”. 2nd example works without issues. $\endgroup$
    – Sanmuten
    Aug 25, 2018 at 15:24

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