Re: Transform list of numbers into pure functions using replace rule
- To: mathgroup at smc.vnet.net
- Subject: [mg89484] Re: Transform list of numbers into pure functions using replace rule
- From: Albert Retey <awnl at arcor.net>
- Date: Tue, 10 Jun 2008 07:14:13 -0400 (EDT)
- References: <g2lb8t$964$1@smc.vnet.net>
Mac wrote:
> Hello,
>
> I'm developed a program to invert satellite observations into
> geophysical variables such as forest biomass. One of the input
> parameters are the errors in the observation channels which can be
> either constant or a function. To be consistent the program expects
> all errors to be functions but they can also be constant functions
> e.g. if the error is 4 then the input parameter is "4&".
>
> I've however hit a problem with the replacement rule that allows me to
> transform all input errors into a function. The following works as
> expected in that constants in the list are transformed into virtual
> functions and functions in the list are left alone.
>
> In[40]:= If[NumberQ[#], ToExpression[ToString[#] <> "&"], #] & /@ {1,
> 2, 3 &, f[x]}
>
> Out[40]= {1 &, 2 &, 3 &, f[x]}
>
> However, I cannot find a replacement rule to do the same job. Here is
> one try:
>
> In[39]:= {1, 2, f[x]} /. x_ /; NumberQ -> Hold[x &]
This is the correct syntax for Condition:
{1, 2, f[x]} /. x_ /; NumberQ[x] -> Function[x]
This is what I would probably do:
{1, 2, f[x]} /. x_?NumericQ -> Function[x]
I would also strongly suggest to not use arguments in your function
descriptions, then you can treat everything the same:
f[x_]:=x^3
parameters = {
1, 2,f, Sin, Abs,
Interpolation[Table[{x, Sin[x^2]}, {x, 0, 1, 0.1}]],
Compile[{x},Exp[1/x]],
Function[{y}, Piecewise[{{Abs[y], y > -10}}]]
}
functions = Replace[parameters, {x_?NumericQ -> Function[x]}, {1}]
Map[#[0.5] &, functions]
note that you need to be careful to make this work with interpolating
and compiled functions, too...
hth,
albert