Page 1

Recursive Data Types

Page 2

Modelling Arithmetic Expressions

Page 3
Modelling Arithmetic Expressions
Page 4

Live Demo

Page 5

Modelling Arithmetic Expressions

Page 6

Example: Evaluation

Page 7
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

Page 9

Brackets

When are brackets needed?

Page 10

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

Making a Show instance

Page 12

Generating arbitrary expressions

Page 13

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

Symbolic Expressions

Page 15

Summary

Page 16

Next time