       RE: Making a function dynamically define another conditional function...

• To: mathgroup at smc.vnet.net
• Subject: [mg21766] RE: [mg21733] Making a function dynamically define another conditional function...
• From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
• Date: Thu, 27 Jan 2000 22:56:46 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```Paul Howland wrote:
-------------------------------
How can I make a function dynamically define a conditional function?

Given a list of arguments {{a,A}, {b,B}, ...} I want to write a function
that will take these arguments, and generate a new function, f say,
which is defined as (for example):
f[x_] := x+a /; x==A
f[x_] := x+b /; x==B
etc.

So, the obvious solution is to define a function as follows:

In := TestFn[data_List] := Module[{args},
ClearAll[f];
Do[
args = data[[i]];
f[x_] = x + args[] /; x==args[],
{i, Length[data]}
]]

and call it using something like TestFn[{{1,2},{3,4},{5,6}}].
But this doesn't work

-------------------------------
I don't feel like figuring out why your method didn't work, but I do have a
solution.
However, are you sure you don't really want to define
f[x_]/;(x==A):=x+a
and likewise for other conditions.

Well I will show how to get the result that I think you were trying to get.
Your definitions of (f) are stored in DownValues[f]. The next line shows the
first and only DownValue in this situation.

In:=
ClearAll[f]
f[x_]:=x+x1/;x==XX1
dv=First[DownValues[f]]

Out=
HoldPattern[f[x_]] :> x + x1 /; x == XX1

DownValues such as the one above are expressions just like anything else in
Mathematica, and you can change parts of this expression. In the next line
ReplacePart does this very nicely. Check the documentation for ReplacePart
to see what's going on here.

In:=
data={{a,A},{b,B},{c,C}};
ReplacePart[dv,data,{{2,1,2},{2,2,2}},{{1,1},{1,2}}]

Out=
HoldPattern[f[x_]] :> x + a /; x == A

The line above changes (x1) to (a) and (XX1) to (A).
The next line does this for each sublist in (data).

In:=
Map[ReplacePart[dv,#,{{2,1,2},{2,2,2}},{{1},{2}}]& ,data]

Out=
{HoldPattern[f[x_]] :> x + a /; x == A, HoldPattern[f[x_]] :> x + b /; x ==
B,
HoldPattern[f[x_]] :> x + c /; x == C}

In the next line I give you (TestFn) which wraps it all together.

In:=
TestFn[data_List]:=(ClearAll[f];
f[x_]:=x+a/;x==A;
With[{dv=First[DownValues[f]]},
DownValues[f]=Map[ReplacePart[dv,#,{{2,1,2},{2,2,2}},{{1},{2}}]& ,data]
]
)

Next I make sure TestFn works.

In:=
TestFn[{{y1,z1},{y2,z2},{y3,z3}}];

In:= ?f

Global`f
f[x_]:=x+y1/;x==z1
f[x_]:=x+y2/;x==z2
f[x_]:=x+y3/;x==z3

--------------------
Regards,
Ted Ersek

On 12-18-99 Mathematica tips, tricks at
http://www.dot.net.au/~elisha/ersek/Tricks.html