Your task involves creating a Haskell function that evaluates an expression represented by a custom syntax tree (IdExpr). This function must interpret basic arithmetic operations (Add, Sub, Mul, Uminus) and resolve identifiers (Id) using a provided association list.
Let's complete the implementation of evalIdExpr using pattern matching for each constructor of IdExpr:
Leaf directly returns the integer value.
Id looks up the string in the association list and defaults to 0 if not found.
Add, Sub, Mul recursively evaluate their operands and apply the respective operation.
Uminus evaluates its operand and applies unary minus.
Here's the full implementation based on the specifications:
module EvalIdExpr (evalIdExpr, testEvalIdExpr) where
import Test.QuickCheck
import Data.List (lookup)
-- | IdExpr is an expression-tree over integers and string identifiers
data IdExpr =
Id String
| Leaf Int
| Add IdExpr IdExpr
| Sub IdExpr IdExpr
| Mul IdExpr IdExpr
| Uminus IdExpr
deriving (Eq, Show)
-- | Assoc is a list of pairs mapping identifier strings to their values.
type Assoc v = [(String, v)]
-- | evalIdExpr evaluates the IdExpr expression-tree.
evalIdExpr :: IdExpr -> Assoc Int -> Int
evalIdExpr expr assoc =
case expr of
Leaf n -> n
Id x -> maybe 0 id (lookup x assoc) -- Uses 'maybe' to provide a default value of 0 if lookup fails.
Add e1 e2 -> evalIdExpr e1 assoc + evalIdExpr e2 assoc
Sub e1 e2 -> evalIdExpr e1 assoc - evalIdExpr e2 assoc
Mul e1 e2 -> evalIdExpr e1 assoc * evalIdExpr e2 assoc
Uminus e -> - (evalIdExpr e assoc)
-- | Test function for evalIdExpr using QuickCheck properties.
testEvalIdExpr :: IO ()
testEvalIdExpr = do
putStrLn "*** Testing evalIdExpr"
quickCheck $ property $ \n -> evalIdExpr (Leaf n) [] == n
quickCheck $ property $ \a b -> evalIdExpr (Add (Leaf a) (Leaf b)) [] == a + b
quickCheck $ property $ \x y ->
let assoc = [("x", x), ("y", y)] in
evalIdExpr (Add (Id "x") (Id "y")) assoc == x + y
quickCheck $ property $ -> evalIdExpr (Uminus (Leaf 5)) [] == -5
quickCheck $ property $ ->
let assoc = [("z", 3)] in
evalIdExpr (Sub (Mul (Id "z") (Leaf 10)) (Leaf 5)) assoc == 25
This implementation covers various cases of the IdExpr data type, allowing you to evaluate arithmetic expressions based on integers and identifiers with given associations. The testEvalIdExpr function includes several QuickCheck properties to validate the correct functionality of evalIdExpr, ensuring it meets the required specifications.
Each property in testEvalIdExpr aims at testing different aspects and constructors of IdExpr, with quickCheck providing automated test cases based on these properties.