       Re: Best practice passing expressions to functions

• To: mathgroup at smc.vnet.net
• Subject: [mg85303] Re: Best practice passing expressions to functions
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Tue, 5 Feb 2008 19:40:35 -0500 (EST)
• Organization: The Open University, Milton Keynes, UK
• References: <fo9gvu\$t1l\$1@smc.vnet.net>

```Remo Aschwanden wrote:

> I want to write procedures that accept expressions as parameters and be
> able define functions based on these expressions, i.e.
>
> f[exp_]:=Module[
>    "g[x_] := exp "
> ]
>
> The code between the " " should clarify what I intend to do. Calling
>    f[x^2-2x+4]
> should lead to the definition of a function (or pattern)
>    g[x_]:=x^2-2x+4;
>
> What's the best way to do this? How can I do this without being
> dependent on the variables used in the expressions ("x")?

One possible way, though I do not know whether it qualifies as best
practice, is as follows.

The first argument of f, exp_, is the expression that is going to be
transformed into a function definition, function definition that depends
on the variable var_, which is passed as second argument and as default
value, say, x.

The transformation rule applied to the pattern p_ looks for a pattern
named p\$ rather than p since Mathematica renames p_ as p\$_ (you can see
that by using the command *Trace*).

In:= f[exp_, var_: x] := g[p_ /. p\$ -> var] := exp

In:= f[x^2 - 2 x y + 4 y]
g

Out= 9 - 2 y

In:= f[x^2 - 2 x y + 4 y, x]
g

Out= 9 - 2 y

In:= f[x^2 - 2 x y + 4 y, y]
g

Out= 12 - 6 x + x^2

Regards,
--
Jean-Marc

```

• Prev by Date: Re: Maximum likelihood and Mathematica
• Next by Date: Re: Best practice passing expressions to functions
• Previous by thread: Re: Best practice passing expressions to functions
• Next by thread: Re: Best practice passing expressions to functions