6

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[1]:= D[x^2, x]
Out[1]= 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[1]:= D1[f_, x_] := Limit[(-f[x] + f[x + a])/a, a -> 0]


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

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


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

Out[3]= 2 x


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

Out[4]= 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?

GarouDan
  • 1,536
  • 1
  • 12
  • 15
  • Such function would consist with a large set of rules: how to treat constants, sums, products, power functions, etc. – yarchik Jun 05 '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 #...&. – GarouDan Jun 05 '20 at 19:55

2 Answers2

6

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}$

MassDefect
  • 10,081
  • 20
  • 30
6
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]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371