Page 1

Symbolic Expressions

Page 2

Arithmetic Expressions

Remember this from the Arithmetic Quiz?

Page 3

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 4

Gathering variables

Page 5

Evaluating Symbolic Expressions

Page 6

The Maybe type

Page 7

Symbolic Differentiation

Page 8
Symbolic Differentiation
Page 9

Smart constructors

Page 10

Simplifying expressions

Page 11

Monadic Expression Evaluation

Page 12
Monadic Expression Evaluation
Page 13

Avoiding division by zero

Page 14

Looking up variables

Page 15

Combining effects?

Page 16

A monad for eval

Page 17

Combining effects

The finished monadic evaluator

evalM :: Expr -> Eval Integer
evalM (Num n) = pure n
evalM (Var x) = lookupVar x
evalM (Add a b) = (+) <$> evalM a <*> evalM b
evalM (Mul a b) = (*) <$> evalM a <*> evalM b
evalM (Div a b) = do x <- evalM a
                     y <- evalM b
                     safeDiv x y

safeDiv x 0 = divByZero
safeDiv x y = pure (x `div` y)
Page 18

Final thoughts on the monadic evaluator