0
$\begingroup$

We can define a function using a variable b that does not appear as an argument, and then using Block, change the output of the function by modifying b. For example, consider the below where b does not appear as an argument to g.

g[a_, x_] := a + x + b

g[1, x]
(* output is 1 + b + x *)

Block[{b = E}, g[1, x]]
(* output is 1 + E + x *)

What I am looking for is essentially the same thing but where b is instead a function f[x] and I can modify f[x] without it appearing as an argument to g. What I want is apparent in the following.

g[a_, x_] := a + x + f[x]

Block[{f[x] = x^2}, g[1, x]]
(* where output would be 1 + x^2 + x *)

Of course, an error appears because Block can't assign a value to a function.

How I get the behavior I want in a decent, safe, and not-so-convoluted way?

Conditions

First, I do not want to have to change the definition of g in any way.

Second, I have considered syntactic replacement with /. but this is not mathematically safe and I am looking for something mathematically safe. For example,

(f[x] + D[f[x], x]) /. f[x] -> x^2

outputs

x^2 + f`[x].

What I am looking for would have the output

x^2 + 2x.

Block, with variable assignment, has the nice behavior. For example, compare the following.

D[y, x] /. y -> x
(* outputs 0 *)

Block[{y = x}, D[y, x]]
(* outputs 1 *)
$\endgroup$
3
  • 3
    $\begingroup$ Does Block[{f=Function[{x}, x^2]}, g[1, x]] solve your problem? $\endgroup$
    – rhermans
    Commented Oct 13, 2021 at 14:38
  • 3
    $\begingroup$ or Block[{f}, f[x_] := x^2; g[1, x]] $\endgroup$
    – Jason B.
    Commented Oct 13, 2021 at 14:41
  • $\begingroup$ @rhermans Both seem to work. If they do not after a deeper look, I will update. Thank you both. $\endgroup$ Commented Oct 15, 2021 at 22:07

0