[Date Index]
[Thread Index]
[Author Index]
Re: Making a function dynamically define another conditional function...
*To*: mathgroup at smc.vnet.net
*Subject*: [mg21762] Re: [mg21733] Making a function dynamically define another conditional function...
*From*: "David Park" <djmp at earthlink.net>
*Date*: Thu, 27 Jan 2000 22:56:42 -0500 (EST)
*Sender*: owner-wri-mathgroup at wolfram.com
Paul,
Here are two approaches:
cdata = {{1, 2}, {3, 4}, {5, 6}};
definef[data_] :=
(Clear[f];
f[x_] :=
Switch[x,
Evaluate[
Sequence @@
Flatten[Join[
Transpose[MapAt[# + x &, Transpose[data], 2]], {{_, 0}}]]]])
definef[cdata]
f /@ Range[5]
{3, 0, 7, 0, 11}
The second approach:
definef2[data_] :=
Module[{i},
Clear[f];
f[x_] =
Sum[KroneckerDelta[x - data[[i, 1]]](x + data[[i, 2]]), {i, 1,
Length[data]}]
]
definef2[cdata]
f /@ Range[5]
{3, 0, 7, 0, 11}
The only disadvantage here is that the function returns 0 for a non-match. Maybe
someone can show how to make it return f[x].
David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/
>
>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[1] := TestFn[data_List] := Module[{args},
> ClearAll[f];
> Do[
> args = data[[i]];
> f[x_] = x + args[[1]] /; x==args[[2]],
> {i, Length[data]}
> ]]
>
>and call it using something like TestFn[{{1,2},{3,4},{5,6}}].
>
>But this doesn't work (see attached notebook) as it appears that
>Mathematica does not evaluate any part of the condition at the time of
>definition, so args[[2]] remains unevaluated. As a consequence, the
>resulting function definition is not properly defined.
>
>So, the obvious solution to this is to wrap Evaluate[] around the
>condition (i.e. define the function as f[x_] = x + args[[1]] /;
>Evaluate[x == args[[2]]]. And this appears to work. If you do ?f, then
>you see a function comprising a number of conditional definitions.
>However, if you come to use the function, then it appears that
>Mathematica does not perform the condition test that appears in the
>definition! It simply uses the first definition it finds.
>
>What is going on?! How can I make this work?
>
>I attach a notebook with example code. [Contact Paul to
>get this notebook - Moderator]
>
>Many thanks for any help.
>
>Paul
>
>
Prev by Date:
**RE: Simplifying Finite Sums With A Variable # of Terms**
Next by Date:
**Re: Efficient Replacement Rules to Matrix?**
Previous by thread:
**Re: Making a function dynamically define another conditional function...**
Next by thread:
**Re: Making a function dynamically define another conditional function...**
| |