views:

168

answers:

1

How can I evaluate an expression, given a list of values for the variables it contains?

eval::[(Variable,Integer)]->Expr->Integer

Example:

eval[("x",2), ("y",4)](Mult(Plus(Var "x") (Const))(Var "y"))= 12
+1  A: 

Variable and Expr are not inbuild types in Haskell.

If you are using a library or working on a part of a larger program maybe it has the capabilities you are after.

If you have defined these types yourself, then its up to you.

If this is for coursework, then you might want to read about grammers and parsing techniques. Try breaking the string up into tokens and constructing a symbolic representation you can evaluate. If you havent found it already http://www.zvon.org/other/haskell/Outputglobal/index.html is a good reference site.

If your into something more heavyweight (and have a firm grip on haskell and monadic programming) then I'd reccomend investing the time in learning to use Parsec http://www.haskell.org/haskellwiki/Parsec.

Akusete