# How can we create functions like Mathematica does?

Simple question. How can we construct functions like Mathematica does?

For example, let's say that we want to create our own D function.

The D function works like:

In:= D[x^2, x]
Out= 2 x


where we can put a function in x and the function will treat this internally in a correct way.

How can we create our D1 function with the same behavior?

Attempts:

In:= D1[f_, x_] := Limit[(-f[x] + f[x + a])/a, a -> 0]

In:= D1[x^2, x]

Out= Limit[(-(x^2)[x] + (x^2)[a + x])/a, a -> 0]

In:= D1[Function[x, x^2], x]

Out= 2 x

In:= D1[#^2 &, x]

Out= 2 x


As we can see, the second and third example work, but I'd like to create a function that would work like in the first example and like the D function.

How can we do this?

• Such function would consist with a large set of rules: how to treat constants, sums, products, power functions, etc. Jun 5 '20 at 19:43
• It is not necessary to have all behavior. It is more about how to use the arguments without using Function[x, ...] or #...&. Jun 5 '20 at 19:55

ClearAll[D1]

D1[f : _Function | _Symbol, x_] := Block[{a}, Limit[(-f[x] + f[x + a])/a, a -> 0]]

D1[f_, x_] := D1[Function[x, f], x]


Now these all return 2 x:

D1[x^2, x]

D1[#^2 &, x]

fun[z_] := z^2; D1[fun, x]

D1[fun[x], x]

• This solution is very interesting, indeed. Is it possible to solve the problem pointed by @yarchik? D1[x^3,x^2] Jun 5 '20 at 21:18
• @GarouDan Pardon me, I'm not familiar with this syntax. D[x^3, x^2] yields General::ivar: x^2 is not a valid variable. >> Jun 5 '20 at 21:26
• Yes, it should give an error in this case. That is what it does. Jun 5 '20 at 21:43

EDIT:

Based on the suggestion by Bob Hanlon, this code should be better as it isolates a from the context of the notebook.

D1[f_, x_] := Module[{a}, Limit[(-f + (f /. {x -> (x + a)}))/a, a -> 0]]


I've tried this on a few functions and it seems to return the same as D, but there are probably edge cases I haven't considered.

D1[f_, x_] := Limit[(-f + (f /. {x -> (x + a)}))/a, a -> 0]
D1[x^2, x]
D1[3 x^3 + y^2, x]
D1[3 Sin[2 x] y^2 + 14, x]


$$2x$$

$$9x^2$$

$$6y^2\cos{2x}$$

• Cool, this seems to be what I was looking for. I'll give it a try and return. Jun 5 '20 at 19:55
• I would use Module[{a}, Limit[ ... ]] to isolate a from the Global context. Jun 5 '20 at 20:13
• @BobHanlon Great idea, thank you! Jun 5 '20 at 20:16
• The second argument needs to be a valid variable. Current version gives zero for D1[x^3,x^2]. Jun 5 '20 at 20:40
• @yarchik I guess it should be set to fail and issue a warning message like D[x^3, x^2] does. Do you think D1[f_, x_Symbol]:=... would be sufficient? Jun 5 '20 at 21:31