How can I evaluate an expression?

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

      

-2


source to share


1 answer


Variable and Expr are not built-in types in Haskell.

If you are using a library or are working on part of a larger program, it may have capabilities that you are using.

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



If this is for term paper, you can read about grammars and parsing techniques. Try to break the string into tokens and create a symbolic representation that you can evaluate. If you haven't found it already http://www.zvon.org/other/haskell/Outputglobal/index.html this is a good reference site.

If you are a bit more heavyweight (and hold on to haskell and monadic programming), I would recommend investing time in learning how to use Parsec http://www.haskell.org/haskellwiki/Parsec .

+1


source







All Articles