Re: Confused about contexts ...
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg570] Re: [mg523] Confused about contexts ...
- From: villegas (Robert Villegas)
- Date: Sun, 19 Mar 1995 05:22:09 -0600
Hello Paul, > I think I'm getting my contexts in a muddle. Can you help me with the > following please? > > Consider the following simple package: > > BeginPackage["Example`"] > test::usage = "Test function" > Begin["`Private`"] > test[a_] := Module[{}, z=Sin[x];Function[x,z]] > End[] > EndPackage[] > > I'm trying to code a function "test" that returns a function as its > argument. > Thus, _what_I'd_like_to_happen_ is this: > > In[1] := > <<Package.m > In[2] := > f = test[a] > Out[2] := > Function[x,Sin[x]] > In[3] := > f[theta] > Out[3] := > Sin[theta] > > However, what actually happens is this: > > In[1] := > <<Package.m > In[2] := > f = test[a] > Out[2] := > Function[Example`Private`x, Example`Private`z] > In[3] := > f[theta] > Out[3] := > Sin[Example`Private`x] The reason the z in Function[x, z] didn't expand to a formula is that Function is one of those things that doesn't evaluate its arguments. If you want to override this behavior, use Evaluate. Here's a simplified example to show what I mean: In[64]:= z = Sin[x] Out[64]= Sin[x] (* The formula ends up being 'z', literally: *) In[65]:= Function[x, z] Out[65]= Function[x, z] (* But we can make the formula be the _value_ of z instead: *) In[66]:= Function[x, Evaluate[z]] Out[66]= Function[x, Sin[x]] There could be another complication to deal with in your usage, because you've got a Function inside of a Module, which is a situation of nested scoping constructs. This is no problem, except that I suspect you might use 'z' as a local variable of the Module (in your real, bigger example, I mean), and also within the body of the Function. This would cause renaming of the Function's variable. A quick example: In[61]:= test[a_] := Module[{z}, z = Sin[x/a]; Function[x, Evaluate[z]] ] In[62]:= test[5] x Out[62]= Function[x$, Sin[-]] 5 One standard way to circumvent this is to disguise the Function by constructing it during the evaluation of the Module. Here's a way to do that: In[68]:= test[a_] := Module[{z}, z = Sin[x/a]; Function @@ {x, z}] In[69]:= test[5] x Out[69]= Function[x, Sin[-]] 5 Hopefully, this will do what you want. Best regards, Robby Villegas