Re: Best practice passing expressions to functions
- To: mathgroup at smc.vnet.net
- Subject: [mg85318] Re: Best practice passing expressions to functions
- From: Jens-Peer Kuska <kuska at informatik.uni-leipzig.de>
- Date: Tue, 5 Feb 2008 19:48:18 -0500 (EST)
- Organization: Uni Leipzig
- References: <fo9gvu$t1l$1@smc.vnet.net>
- Reply-to: kuska at informatik.uni-leipzig.de
Hi,
SetAttributes[defineAFunction, HoldFirst]
defineAFunction[name_Symbol, expr_] :=
Module[{vars},
vars = Select[Cases[expr, _Symbol, Infinity],
Context[#] =!= "System`" &];
SetDelayed @@ {name @@ (Pattern[#, Blank[]] & /@ vars), expr}
]
and after
defineAFunction[blub, Sin[Pi*x] + y*z - Log[q]]
you have
In[]:=blub[x, y, z, q]
Out[]=x y - Log[z] + Sin[\[Pi] q]
Regards
Jens
Remo Aschwanden wrote:
> Hi
>
> 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")?
>
> Thank you.
> Remo A.
>
>