       • 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
>

> 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 :=

> 		<<Package.m
> 	In :=

> 		f = test[a]
> 	Out :=
> 		Function[x,Sin[x]]
> 	In :=

> 		f[theta]
> 	Out :=

> 		Sin[theta]
>
> However, what actually happens is this:
>

> 	In :=

> 		<<Package.m
> 	In :=

> 		f = test[a]
> 	Out :=
> 		Function[Example`Private`x, Example`Private`z]
> 	In :=

> 		f[theta]
> 	Out :=
> 		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:= z = Sin[x]

Out= Sin[x]

(* The formula ends up being 'z', literally: *)

In:= Function[x, z]

Out= Function[x, z]

(* But we can make the formula be the _value_ of z instead: *)

In:= Function[x, Evaluate[z]]

Out= 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:= test[a_] := Module[{z}, z = Sin[x/a]; Function[x, Evaluate[z]] ]

In:= test

x
Out= 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:= test[a_] := Module[{z}, z = Sin[x/a]; Function @@ {x, z}]

In:= test

x
Out= Function[x, Sin[-]]
5

Hopefully, this will do what you want.

Best regards,

Robby Villegas

```

• Prev by Date: Re: Functions, Part 1
• Next by Date: Re: Functions, Part 1