MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Putting an expression into a module

  • To: mathgroup at smc.vnet.net
  • Subject: [mg84902] Re: Putting an expression into a module
  • From: Albert Retey <awnl at arcor.net>
  • Date: Fri, 18 Jan 2008 05:52:27 -0500 (EST)
  • References: <fmngh8$3fl$1@smc.vnet.net>

Hi,

> Suppose you have generated a long symbolic expression, e, and now wish
> to  use the expression inside a Module. One method would be to cut-and-
> paste the expression into the Module but how do you do this without
> cutting-and-pasting?
> Below in a warm up problem I first get what I want by cutting-and-
> pasting and then try various combinations of Hold, ReleaseHold and
> Evaluate. These don't work (why?) but how can it be done?

Usually my prefered way to insert evaluated expressions into a held 
expression is using by using With:

In[24]:= e = y^2 - x^2

Out[24]= -x^2 + y^2

In[25]:= With[{expr = e},
  ClearAll[f];
  f[x_] := Module[{y}, y /. FindRoot[expr, {y, 1}]]
  ]

In[26]:= DownValues[f]

Out[26]= {HoldPattern[f[x$_]] :>
   Module[{y$}, y$ /.FindRoot[-x^2 + y^2, {y$, 1}]]}

Note that this kind of works but of course messes up the scoping in this 
case. This is why in situations like that another thing I have made good 
experience with is to use functions instead of expressions, like here:

In[36]:= With[{fun = Function @@ {{x, y}, e}},
  ClearAll[f];
  f[x_] := Module[{y}, y /. FindRoot[fun[x, y], {y, 1}]]
  ]

As you can see from this, this works without any other workarounds to 
avoid problems with the scoping constructs:

In[38]:= DownValues[f]

Out[38]= {HoldPattern[f[x$_]] :>
   Module[{y$},
    y$ /.FindRoot[Function[{x, y}, -x^2 + y^2][x$, y$], {y$, 1}]]}

hth,

albert


  • Prev by Date: [M6] Aligning graphics on frame boundaries
  • Next by Date: Re: Wavelet "filter"?
  • Previous by thread: Re: Putting an expression into a module
  • Next by thread: Re: Putting an expression into a module