1
$\begingroup$

Consider the following:

rule = f[x] -> Sin[x]

if I now do, say:

f[y] /. rule

this does not work, because the rule wants the argument to specifically be x. Of course, I could do:

f[x] /. rule /. x -> y

but I really would be able to "clean" the rule of the input. As an example, If we use NDSolve to solve an ODE, we obtain a rule of the form:

{f -> InterpolatingFunction["stuff"]}

this is nice insofar that I can apply this rule to f, where the argument can be anything I wish. So, the question is, If I ALREADY have a rule as above, is there a nice way to "remove" the "[x]" part of all the functions, in the sense described above?

$\endgroup$
2
  • 2
    $\begingroup$ Why not use rule = f -> Sin? $\endgroup$
    – Carl Woll
    Commented Jan 31, 2019 at 20:33
  • $\begingroup$ The reason is that the rule I have is obtained by solving an algebraic equation for a variable f(x). The output of Solve gives you a rule, which then has the explicit argument input, unfortunately. That is why I specified how to change the rule in the desired way. Except if we can force Solve to behave like NDSolve, insofar that it "forgets" about the argument (both for the LHS and RHS of the rule)? $\endgroup$
    – Patrick.B
    Commented Feb 1, 2019 at 14:52

2 Answers 2

1
$\begingroup$

While John Doty's answer works pretty well, if you want to obtain a pure function as rhs of your rule like in your InterpolatingFunction example, you can do something like

rule = f[x] -> Sin[x];
newrule = f -> Block[
 {x},
 Function @@ List[{x}, f[x] /. rule]
]
(*f -> Function[{x}, Sin[x]]*)
$\endgroup$
2
  • $\begingroup$ Quite interesting. I am new to Mathematica and I have never encountered the use of @@ before. What is the use of it? $\endgroup$
    – Patrick.B
    Commented Feb 1, 2019 at 14:56
  • 1
    $\begingroup$ f @@ expr (spaces are optional) is a shortcut for Apply[f, expr], which changes the head of expr to f. Consult Apply in the Documentation Center for details. $\endgroup$ Commented Feb 1, 2019 at 15:38
5
$\begingroup$

It's just like defining a function. Make x the name of a pattern, not a literal symbol:

rule = f[x_] -> Sin[x]
f[y] /. rule
(* Sin[y] *)
$\endgroup$
2
  • $\begingroup$ If you do this, you should generally use RuleDelayed (:>) instead of Rule (->). $\endgroup$ Commented Feb 1, 2019 at 9:52
  • $\begingroup$ I see! It really was a simple answer. Thank you very much! $\endgroup$
    – Patrick.B
    Commented Feb 1, 2019 at 14:49

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.