I'm trying to make a function for syntax tree arithmetic operations and thus far I'm almost where I want it to be. In the code I attach you can see my current function definitions. eval
is the function that decides what to do with each operation and foldAndPropagateConstants
is the main function. parse
is a simple parser that takes a String
of a mathematical expression and returns the equivalent tree. e.g.
ghci> parse "3+x"
BinaryOperation Plus (Leaf (Constant 3)) (Leaf (Variable "x"))
The issue I'm facing is how to have the evaluated values to be used in subsequent operations. For example, this operation should work as follows:
ghci> foldAndPropagateConstants [("x", parse "1+2+3"), ("y", parse "5*x + 7")]
[("x",Leaf (Constant 6)),("y",Leaf (Constant 37))]
Notice that the function should use the value that "x"
got, when calculating the value for "y"
. Thing is, I can't seem to find a way to use "x"
's value in my eval
function.
--foldAndPropagateConstants :: [(String, Exprv)] -> [(String, ExprV)]
eval :: ExprV -> Int
eval (Leaf (Variable n)) = --this part is what's missing
eval (Leaf (Constant n)) = n
eval (BinaryOperation Plus expr1 expr2) = eval expr1 + eval expr2
eval (BinaryOperation Times expr1 expr2) = eval expr1 * eval expr2
eval (UnaryOperation Minus expr1) = -1 * eval expr1
foldAndPropagateConstants (x:xs) = [(fst x, parse (show (eval(snd x)))) ] : foldAndPropagateConstants xs
foldAndPropagateConstants _ = []