### Prolog - Simple Symbolic Differentiator.

 LA home Computing Logic  Prolog   Intro.   Syntax   Examples    Windsor    Append    Aunt    Solar    Diff    Tree    Witch
The rules of symbolic differentiation, such as,
```d          d       d
- (A+B) =  - A  +  - B
dx         dx      dx
```
can be easily expressed in Prolog:
```diff(plus(A,B), X, plus(DA, DB))
<= diff(A, X, DA) and diff(B, X, DB).

diff(times(A,B), X, plus(times(A, DB), times(DA, B)))
<= diff(A, X, DA) and diff(B, X, DB).

equal(X, X).
diff(X, X, 1).
diff(Y, X, 0) <= not equal(Y, X).

? diff( plus(times(x, x), times(3,x)), x, Dx).

{ Symbolic Differentiator. }

```

The symbolic differentiator gives the correct answer as the first solution (it is not in simplified form but that could be achieved). However other incorrect "solutions" are also output. These are caused by the rule diff(Y, X, 0) being too general. It only holds if not (X=Y).

### Negative Information.

The problem with the first symbolic differentiator can be fixed by insisting that  not (X=Y)  for  diff(Y,X,0):
```diff(plus(A,B), X, plus(DA, DB))
<= diff(A, X, DA) and diff(B, X, DB).

diff(times(A,B), X, plus(times(A, DB), times(DA, B)))
<= diff(A, X, DA) and diff(B, X, DB).

atomic(x). atomic(y). atomic(3).

equal(X, X).

diff(X, X, 1).
diff(Y, X, 0) <= atomic(Y) and not equal(Y, X).

? diff( plus(times(x, x), times(3,x)), x, Dx).

{ Symbolic Differentiator. }

```
Production Prolog systems have the full set of comparison operators built in but unification, equal(X,X), is used here.

It is a good exercise to write Prolog to simplify the result of differentiation, for example, to replace times(1, x)) with x.

Just in case you were wondering, the differentiator cannot be run backwards to get an integrator, which is a pity. It is possible to write a program to perform symbolic integration in Prolog, but it is far from easy – in any programming language – if more than polynomials must be handled.