Message Boards Message Boards

Evaluate a global expression within functions?

GROUPS:
POSTED BY: Werner Geiger
Answer
2 months ago
POSTED BY: George Varian
Answer
2 months ago

Sorry for confusion. I noticed that my code is nonsense and edited my original post meanwhile. I'll come back with corrected questions.

POSTED BY: Werner Geiger
Answer
2 months ago

Meanwhile I have changed my faulty testprogram from my first post (sorry about that). It now prints exp within the functions and not after the call.

Now everything works as expected by using Replace. No matter if the functions are defined with or without Module. My mistake was, that I used the same name "a" for function parameters and the global expression exp=a*x.

It's still a bit strange and I do not fully understand it. But it works.

If[True,
 ClearAll["Global`*"]; 
 exp = a*x; Print["#1: Global exp: ", exp, "\n\tok"];
 a = 3; Print["#2: a=3 substituted: ", exp, "\n\tok"];
 a =.; Print["#3: a reset: ", exp, "\n\tok"];

 f14[aparm_] := 
  Print["#14: a=", aparm, 
   " substituted within a function by Replace: ", exp /. a -> aparm, 
   "\n\tok"];
 f14[3];
 f14[myA];

 f16[aparm_] := 
  Module[{}, 
   Print["#16: a=", aparm, 
     " substituted within a function-Module by Replace: ", 
     exp /. a -> aparm, "\n\tok"];
   ];
 f16[3];
 f16[myA];
 ]
#1: Global exp: a x
    ok
#2: a=3 substituted: 3 x
    ok
#3: a reset: a x
    ok
#14: a=3 substituted within a function by Replace: 3 x
    ok
#14: a=myA substituted within a function by Replace: myA x
    ok
#16: a=3 substituted within a function-Module by Replace: 3 x
    ok
#16: a=myA substituted within a function-Module by Replace: myA x
    ok
POSTED BY: Werner Geiger
Answer
2 months ago

Group Abstract Group Abstract