I am trying to define a function which would take a Double -> Double function and return its mathematical derivative. I have tried doing the following:
der :: (Double -> Double) -> (Double -> Double)
der f
| f == exp = exp
| otherwise = undefined
but Haskell does not support == on Double -> Double values. Is what I am trying to do impossible in Haskell?
Yes, what you are trying to do is impossible in Haskell, and in general: deciding whether two functions are equal for all possible inputs (without just checking every input value, if that is even possible) is equivalent to solving the Halting problem.
However, in your specific case, you can get around it, using a custom type that simulates a
Double(i.e. has the same instances, and so can be used in place of it) but instead of evaluating to a number, it constructs an abstract representation of the operations the functions does.Exprrepresents the right-hand side of a mathematical function definitionf(x) = ....Then, using rank-2 types, you can define conversion functions that convert between functions that take any
FloatingandExprs:You can also define a function
diff :: Expr -> Exprthat differentiates the expression:Having all these parts should mean that you can differentiate (some) functions, e.g.
Caveats:
Eqinstance forExpris tricky (it is equivalent to the Halting problem, since it is basically asking if two functions are equal),