views:

244

answers:

2

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".

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

+1  A: 

Well, can't you apply pattern matching to the individual cases?

simplify (Plus (Const 0) (Expr x)) = simplify (Expr x)
simplify (Plus (Expr x) (Const 0)) = simplify (Expr x)
simplify (Mult (Const 0) _) = Const 0
simplify (Mult _ (Const 0)) = Const 0
– … and so on

EDIT: Yes, of course … recursion added.

Konrad Rudolph
The syntax here is a bit off - you'll need to put parens around eg, (Plus (Const 0) (Expr x)) - but otherwise on the right track
bdonlan
A: 

I don't know much about haskell, but essentially your are going to want to do an expression tree traversal.

the tree is EXP: (operator) (EXP) (EXP) EXP: (const) EXP: (var)

then your simplify becomes heres the psuedo code

simplify(Exp e)
if (e is const) return e
else if (e is var) return e
else
{//encode simplification rules
    Exp left = simplify(e.left)
    Exp right = simplify(e.right)
    if(operator is PLUS)
    {
        if(left == 0) return right;
        if(right == 0) return left;
    }
    else if(operator is MULT)
    {
        if(left == 1) return right;
        if(right == 1) return left;
        if(left == 0) return 0;
        if(right == 0) return 0;
    }
//and so on for other operators
}

this is sort of java esque but i think the idea is there, essentially youre going to have to do a tree traversal.

luke