How to write arithmetic expression to evaluate differentiation in haskell
I want the user to enter as Diff x^3 and get the answer as 3x^2
How can I wr开发者_如何学Goite the arithmetic expression for this evaluation?
What is the best way to do this in haskell?
Thank you.
Here's an extremely simple version; feel free to extend - add evaluation, several variables, more functions, grouping of terms, pretty printing, parsing etc.
data Expr = Const Float | Var | Sum Expr Expr | Product Expr Expr
deriving Show
diff :: Expr -> Expr
diff (Const _) = Const 0
diff Var = Const 1
diff (Sum f g) = Sum (diff f) (diff g)
diff (Product f g) = Sum (Product f (diff g)) (Product (diff f) g)
Here is a blog post that gives a neat way using overloading. Or here.
Automatic differentiation, as given by supercooldave, is a bit heavyweight for what you want. Better and simpler to start with what you want, sans differentiation -- a way to parse strings into expression trees, to evaluate them, and to show them. Once you have that down, then you just need to code up the chain rule and a few primitives!
Try a simple structure at first like
Expr = ENum Double | EVar String | EBinOp BinOp Expr Expr | EUnaryOp UnOp Expr
BinOp = Mul | Add | Div | Pow
UnOp = Diff String | Negate | Abs
精彩评论