1

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 *)
Carl Woll
  • 130,679
  • 6
  • 243
  • 355
Sanmuten
  • 93
  • 5
  • 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. – Mr.Wizard Aug 25 '18 at 15:56

3 Answers3

1

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

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • @Sanmuten What is not working? – Carl Woll Aug 24 '18 at 20:31
  • 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. – Sanmuten Aug 25 '18 at 15:24
1
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

kglr
  • 394,356
  • 18
  • 477
  • 896
1

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]
Alan
  • 13,686
  • 19
  • 38