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
    $\begingroup$ Why not use rule = f -> Sin? $\endgroup$ – Carl Woll Jan 31 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 Feb 1 at 14:52
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$
  • $\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 Feb 1 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$ – Anton.Sakovich Feb 1 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$
  • $\begingroup$ If you do this, you should generally use RuleDelayed (:>) instead of Rule (->). $\endgroup$ – Sjoerd Smit Feb 1 at 9:52
  • $\begingroup$ I see! It really was a simple answer. Thank you very much! $\endgroup$ – Patrick.B Feb 1 at 14:49
0
$\begingroup$

To remove the [x] part of all the functions in your rule = f[x] -> Sin[x], you can do

fixedRules = rule /. f[x] -> f;

Then, fixedRules will behave as needed for any argument.

f[y] /. fixedRules
(*Sin[y]*)
$\endgroup$
  • $\begingroup$ Should be fixedRules = rule /. f_[x] -> f. And that only works in simple cases. rule = f[x] -> Sin[x] + 1 breaks it. $\endgroup$ – John Doty Jan 31 at 21:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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