Defining a function within a module
- To: mathgroup at smc.vnet.net
- Subject: [mg22462] Defining a function within a module
- From: "David Park" <djmp at earthlink.net>
- Date: Wed, 8 Mar 2000 02:21:59 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
Dear MathGroup,
I wish to define and use a function within a module, using an expression passed to
the module. This is a simpler example, where I simply return the function. If I use
the mkfun routine, described in Section 2.6.5 of the Mathematica Book, everything
works. Here x is a global variable without a value, and expr is an expression
containing x.
foo1[expr_] :=
Module[{mkfun},
mkfun[x_, body_] := Function[x, body];
mkfun[x, expr]
]
foo1[x^2]
Function[x, x^2]
But, since mkfun simply substitutes x and body into the unevaluated Function, the
following should also work.
foo2[expr_] :=
Module[{g},
g = Hold[Function[x, body]] /. body -> expr;
ReleaseHold[g]
]
foo2[x^2]
Function[x, x^2]
It does, but body is a global variable and so the routine will fail if body has a
value. Therefore, make body internal to the module.
foo3[expr_] :=
Module[{g, body},
g = Hold[Function[x, body]] /. body -> expr;
ReleaseHold[g]
]
foo3[x^2]
Function[x$, x^2]
This does not work because the variable name has been changed. Why was it changed
even though it was within a Hold? Why did making body a Module variable rather than a
global variable cause it to be changed? But in the following routine, we can change
x$ back to x.
foo4[expr_] :=
Module[{g, body},
g = Hold[Function[x, body]] /. body -> expr;
ReleaseHold[g] /. x$ -> x
]
foo4[x^2]
Function[x, x^2]
In fact, we don't even need the Hold, since it didn't work anyway.
foo5[expr_] :=
Module[{},
Function[x, expr] /. x$ -> x
]
And here is an even simpler method for obtaining our function.
foo6[expr_] :=
Module[{g},
g[x, expr] /. g -> Function
]
foo6[x^2]
Function[x, x^2]
I wish I had a better understanding of when Function does and does not change the
variable name.
David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/
- Follow-Ups:
- Re: Defining a function within a module
- From: Hartmut Wolf <hwolf@debis.com>
- Re: Defining a function within a module