Example: Evaluation
eval :: Expr -> Integer
eval (Num n) = n
eval (Add a b) = eval a + eval b
eval (Mul a b) = eval a * eval b
Page 8
Showing expressions with brackets
showExpr :: Expr -> String
showExpr (Num n) = show n
showExpr (Add a b) = showExpr a ++ "+" ++ showExpr b
showExpr (Mul a b) = showFactor a ++ "*" ++ showFactor b
showFactor :: Expr -> String
showFactor (Add a b) = "(" ++ showExpr (Add a b) ++ ")"
showFactor e = showExpr e
Page 11
Completing the arithmetic quiz program
main = do putStrLn "Welcome to the Arithmetic Quiz!"
forever quiz
quiz =
do e <- generate (rExpr 3)
putStr ("\n"++show e++" = ")
answer <- getLine
let correct = show (eval e)
putStrLn (if answer == correct
then "Correct!"
else "Wrong! The correct answer is: "++correct)
Page 14