I've been trying to define a function compdiff
on the Wolfram Language that takes two mathematical expressions f
and g
and a variable x
as input and outputs the difference of their compositions f[g[x]]-g[f[x]]
(a sort of commutator if you are into abstract algebra).
For example: compdiff[x^2,x+1,x] = (x+1)^2-(x^2+1)
.
I've tried with
compdiff[f_,g_,x_]:= Composition[f,g][x]-Composition[g,f][x]
and
compdiff[f_,g_,x_]:= f @* g @ x-g @* f @ x
but when I input
compdiff[x^2,x+1,x]
it outputs
(x^2)[(1 + x)[x]] - (1 + x)[(x^2)[x]]
What am I doing wrong?