2018-11-25 17:30
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
Symbolic Expressions

What we had before

Page 16
Symbolic Expressions

How about expressions with variables in them?

data Expr = Num Integer
          | Var Name       -- new
          | Add Expr Expr
          | Mul Expr Expr

type Name = String
Page 17

Gathering variables

Page 18

Substitution

Replacing variables with something else

Page 19

Evaluating Symbolic Expressions

Page 20

The Maybe type

Page 21

Symbolic Differentiation

Page 22
Symbolic Differentiation
Page 23

Smart constructors

Page 24

Simplifying expressions

Page 25

Summary

Page 26

Next time