# How to use a function definition in another function

For example (not what I really need but will fur sure answer my question)

f[x_]:=Sin[x];
der[x_]:=D[f[x],x]

At least this was my idea, but it does not work at all. You can see that the definition of der[x] includes the definition of another function. And I want to get its derivative.

• Use Set rather than SetDelayed: der[x_] = D[f[x], x] or use Evaluate: der[x_] := Evaluate@D[f[x], x]. In either case, afterwards look at ?der Dec 22, 2016 at 16:42
• Your function works as expected for me. If you want to evaluate functions of the form Sin[u] change der to der[u_, x_] := D[f[u], x], allowing you to call der[x^2, x] Dec 22, 2016 at 16:45

So this is an evaluation order problem, my quick fix would be to do the derivative using a different variable then substitute x back in at the end:

f[x_] := Sin[x];
der[x_] := D[f[y], y] /. y -> x;
der[.5]
(*0.877583*)
• One would do well to make y local via Module I think, or use a Formal Symbol. +1 however. Dec 22, 2016 at 17:22
• @Mr.Wizard I believe a formal symbol would suffer the same pitfall as Slot[1] in my answer (e.g. Sin[\[FormalY] * x]). Since a formal symbol is more likely to be used as a parameter than Slot[], perhaps it is less safe. Dec 22, 2016 at 19:01
• @Michael If I follow your logic the session-unique Module variable is OK however, correct? Dec 22, 2016 at 22:18
• @Mr.Wizard Yes, it should be. It seems the system will bump the module number up if someone decides y\$13214 is their favorite parameter name, and the next module number is 13214. So a conflict shouldn't arise, AFAICT. Dec 23, 2016 at 0:12
• I can confirm that in my case wrapping the body in a Module was what I needed for the gradient of a bivariate function f, like gradfun[x_, y_] := Module[{a, b}, D[f[a, b], {{a, b}}] /. {a -> x, b -> y}];. Very helpful tip, thanks! Sep 27, 2019 at 11:12

Two more ways:

der[x_] := f'[x];

der[x_] := With[{df = D[f[#], #]}, df &[x]];

The second way follows the way the system implements f' (Derivative), so they're as safe as Mathematica. However, both solutions above suffer the same restriction that Derivative does:

This is okay:

ff[x_] := Sin[3 * x];
der[x_] := ff'[x];
der[x]
(*  3 Cos[3 x]  *)

But not this:

ff[x_] := Sin[# * x];
der[x_] := ff'[x];
der[x]
(*  2 x Cos[x^2]  *)

What happened to the coefficient #??? (For a hint, use Trace.)

You can check directly that ff'[x] misbehaves:

ff'[x]
D[ff[x], x]
(*
2 x Cos[x^2]
Cos[x #1] #1
*)

Moral: Slot[] is not safe as a parameter when differentiating.

Try this

f = Sin[#] &
der = D[#, x] &
der[f[x]]

or this

der[f_[x]] = d[f[x], x]
l[x_] = a x + b x^2
der[l[x]]

Normally your definition should works --- it works on my computer. Restart the kernel.