To complete the implementation of this Haskell module, we need to provide an…
- User
To complete the implementation of this Haskell module, we need to provide an implementation for the
evalIntExprfunction. Currently, it just raises aTODOexception using the built-inerrorfunction. We want to replace this implementation with one that actually computes the value of anIntExprtree.Here's an example implementation of
evalIntExprthat performs the computation recursively:haskellevalIntExpr :: IntExpr -> Int evalIntExpr (Leaf i) = i evalIntExpr (Add e1 e2) = evalIntExpr e1 + evalIntExpr e2 evalIntExpr (Sub e1 e2) = evalIntExpr e1 - evalIntExpr e2 evalIntExpr (Mul e1 e2) = evalIntExpr e1 * evalIntExpr e2 evalIntExpr (Uminus e) = negate (evalIntExpr e)This implementation checks whether the
IntExpris a leaf node or not. If it is, it simply extracts the integer value stored at the leaf. Otherwise, it applies the corresponding arithmetic operation on the results of computing the values of its child nodes. Note thatnegateis used instead of multiplying by -1 because it has better performance characteristics.With this implementation, the QuickCheck properties defined in
testEvalIntExprshould now pass successfully. However, since those tests have already been executed during the initial loading of the module, you won't see them being re-executed when defining the new implementation. You may add additional unit tests to ensure correctness. For instance, here's an example set of unit tests that check various edge cases:haskellunitTestEvalIntExpr :: Test unitTestEvalIntExpr = TestList [ TestLabel "Zero" $ TestCase $ assertEqual "" 0 (evalIntExpr zeroExpr), TestLabel "One" $ TestCase $ assertEqual "" 1 (evalIntExpr oneExpr), TestLabel "Negative One" $ TestCase $ assertEqual "" (-1) (evalIntExpr negativeOneExpr), TestLabel "Positive Multiplication" $ TestCase $ assertEqual "" 12 (evalIntExpr posMultExpr), TestLabel "Negative Multiplication" $ TestCase $ assertEqual "" (-36) (evalIntExpr negMultExpr), TestLabel "Complex Expression" $ TestCase $ assertEqual "" (-6) (evalIntExpr complexExpr) ] where zeroExpr = Uminus (Uminus (Leaf 0)) oneExpr = Uminus (Uminus (Leaf 1)) negativeOneExpr = Uminus (Leaf 1) posMultExpr = Mul (Leaf 2) (Leaf 6) negMultExpr = Mul (Uminus (Leaf 6)) (Leaf 6) complexExpr = Mul (Leaf 4) (Sub (Add (Leaf 3) (Uminus (Leaf 33))) (Leaf 20)) - Assistant