views:

559

answers:

5

How can I simplify a basic arithmetic expression?

e.g.

module ExprOps where 

simplify :: Expr -> Expr
simplify (Plus(Var"x") (Const 0)) = Var "x"

What do I have to do?

A: 

Are we talking rationals here, like GMP's rationals? If so, then one could simplify a division by making the second argument into its reciprocal and then multiplying.

Apart from that, multiplication is addition done more than once, and division is subtraction done more than once.

As Mitch has said in the comments, we could do with some more information about what you're trying to simplify.

boost
A: 

e.g module ExprOps where

simplify :: Expr -> Expr

simplify (Plus(Var"x") (Const 0)) = Var "x"

what do i have to do?

A: 

module Expr where

-- Variables are named by strings, assumed to be identifiers. type Variable = String

-- Representation of expressions. data Expr = Const Integer | Var Variable | Plus Expr Expr | Minus Expr Expr | Mult Expr Expr deriving (Eq, Show)

The simplifications I have in mind are 0*e = e*0 = 0 1*e = e*1 = 0+e = e+0 = e-0 = e and simplifying constant subexpressions, e.g. Plus (Const 1) (Const 2) would become Const 3. I would not expect variables (or variables and constants) to be concatenated: Var "st" is a distinct variable from Var "s".

What I want to achieve is to create a module like the one above that uses a function called simplify :: simplify Expr->Expr

+3  A: 

Well, you have the right general model. You just need more rules and to recursively apply the simplification process.

simplify :: Expr -> Expr 
simplify (Mult (Const 0) x) = Const 0 
simplify (Mult x (Const 0)) = Const 0
simplify (Plus (Const 0) x) = simplify x
simplify (Plus x (Const 0)) = simplify x 
simplify (Mult (Const 1) x) = simplify x 
simplify (Mult x (Const 1)) = simplify x 
simplify (Minus x (Const 0)) = simpify x
simplify (Plus (Const x) (Const y)) = Const (x + y)
simplify (Minus (Const x) (Const y)) = Const (x - y)
simplify (Mult (Const x) (Const y)) = Const (x * y)
simplify x = x
Edward Kmett
+1  A: 

thanks Edward that was very helpfull do you mean that i need more complicate expression?