tags:

views:

164

answers:

3

I want the user to enter as Diff x^3 and get the answer as 3x^2

How can I write the arithmetic expression for this evaluation?

What is the best way to do this in haskell?

Thank you.

+2  A: 

Here is a blog post that gives a neat way using overloading. Or here.

supercooldave
Thanks a lot I will have to look into this deeply.I only have the basic knowledge in haskell.But I really like to make a scientific calculator and include functions for differentiation and other calculations.Thanks again.
sunshine
A: 

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
sclv
+3  A: 

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)
sdcvvc
Thanks so much.I was trying to work with this example?But I had got some errors.What would be a sample expression that I could use with sum??
sunshine
@sunshine: `Sum Var (Const 2)` is x+2; `Sum (Product Var Var) (Product Var (Product Var Var))` is x^2+x^3.
sdcvvc