Split your string into S-expression (although this is usually accepted in the Lisp context, you can do the equivalent thing in most cases in any language), the easiest way is with lex / yacc or the equivalent, and then write a recursive "output" function. In the OCaml-ish dialect, something like this:
let rec derive var = function | Const(_) -> Const(0) | Var(x) -> if x = var then Const(1) else Deriv(Var(x), Var(var)) | Add(x, y) -> Add(derive var x, derive var y) | Mul(a, b) -> Add(Mul(a, derive var b), Mul(derive var a, b)) ...
(If you don’t know the OCaml syntax - derive is a two-parameter recursive function with the first parameter the variable name and the second in consecutive lines, for example, if this parameter is a structure of the Add(x, y) form, return the Add structure constructed from two fields , with the values of the derivatives of x and derivatives of y , and similarly for other cases that derive can receive as a parameter; _ in the first pattern means "match something")
After that, you may have some cleaning function to remove the resulting expression (reduction of fractions, etc.), but it becomes complicated and is not necessary for the output itself (i.e. what you get without it, is still the correct answer).
When your s-exp conversion is complete, convert the resulting s-exp to lowercase, again with a recursive function
source share