0
$\begingroup$

I want to replace an expression inside a function. Let's say that I have a following function

f1 = Interpolation[Table[{x, Exp[x]}, {x, 0, 100}]];
{f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100} /. {t_[i__] :> t[i][0]}

What I expect is {f1[g[$123,5][0], f1[h[$123, 5][0]]}. Instead of that, I get the following result:

{InterpolatingFunction[{{0, 100}}, <>][g[$123, 5]] == 100, 
  InterpolatingFunction[{{0, 100}}, <>][h[$123, 5]] == 100}[0]

Does anybody know how to do this?

$\endgroup$
0

2 Answers 2

2
$\begingroup$
{f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100} /. t_[i : _[__]] :> t[i[0]]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ Thanks! That's a really elegant way to solve this problem! $\endgroup$
    – 407PZ
    Commented Nov 18, 2016 at 0:06
1
$\begingroup$

You are hitting two problems here:

  1. Once you assign to f1 it will get replaced by the obtained InterpolatingFunction. If you want to see the result without the latter in doing your substitution, you need to explicitly prevent that. For example, by temporarily defining a local variable of the same name (by enclosing in Module[{f1}, (...)]). A neat trick is to locally redefine f1 to something that looks like f1 in output, for example a string "f1" (see below). NB: the best would be not to assign anything f1 prior to your replacement command at all. Does the first line really need to come first?

  2. You want to match parts of both items of the list {f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100} against t_[i__] but the list itself also satisfies this. For Mathematica,

    {f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100}
    

    is no different from

    List[f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100]
    

So even if you do

With[{f1 = "f1"}, {f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100} /. {t_[i__] :> t[i][0]}]

it does not produce the desired result:

{f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100}[0]

You can see that the [0] got appended to the list. If you are sure of the contents of the list being equalities, I would rather do something like

{f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100} /. {a_ == b_ :> a[0] == b}

or (as the above will still suffer from the substitution for f1), with the string trick,

With[{f1 = "f1"}, {f1[g[$123, 5]] == 100, f1[h[$123, 5]] == 100} /. {a_ == b_ :> a[0] == b}]

{f1[g[$123, 5]][0] == 100, f1[h[$123, 5]][0] == 100}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.