Group Abstract Group Abstract

Message Boards Message Boards

0
|
9.3K Views
|
3 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Evaluate a global expression within functions?

Posted 8 years ago
POSTED BY: Werner Geiger
3 Replies
Posted 8 years 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
Posted 8 years 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
Posted 8 years ago

From documentation:

-SetDelayed has attribute HoldAll, rather than HoldFirst.

Evaluate[expr] causes expr to be evaluated even if it appears as the argument of a function whose attributes specify that it should be held unevaluated.

Thus in F5 ,the right hand side of the SetDelayed is evaluated

f5[a_] := Evaluate[exp]

This shows what Mathematica sees.

?f5
    Global`f5
    f5[a_]:=a x

a is recognized as a parameter in the right hand side of the function f5. Parameters are "renamed" so as not to conflict with globals. Maybe this is what you want:

f10[parameterA_] := (a = parameterA; exp)
f10[3]
    3 x
POSTED BY: George Varian
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard