Page 1

Parsing

"(1+2)*3"

Page 2
Parsing
Page 3

Show and Read

Page 4

Show and Read 2

Page 5

Grammars

Page 6

The use of grammars

Page 7

The purpose of a parser

A parser usually does two things

Page 8

The parsing problem

Page 9

Writing parsers in Haskell

Page 10

Parsing libraries in Haskell

There is some similarity between parsing and generating random test data

Page 11

A simple Parsing Library in Haskell

Page 12

Parsing sequences

Page 13

Running a parser and the Maybe type

Page 14

Examples

Page 15

Exercise

Page 16

Our first parser (live demo)

Page 17

Our first parser

Page 18

Writing the same parser directly

Page 19

A grammar for expressions

Page 20

A new grammar for expressions

Page 21

A parser for expressions (version 1)

expr, expr', term, term', factor :: Parser Expr
expr  = expr' <|> term
expr' = do t <- term
           char '+'
           e <- expr
           return (Add t e)

term  = term' <|> factor
term' = do f <- factor
           char '*'
           t <- term
           return (Mul f t)

factor = do n <- number; return (Num n)
         <|>
         do char '('
            e <- expr
            char ')'
            return e
Page 22

Testing the parser

Page 23

Problems

Page 24

Adjusting the grammar

Page 25

The new parser

Page 26

Two useful parsing combinator

Factoring out the common pattern

Page 27

A few more combinator from the library

Page 28

A more elegant expression parser

Page 29

Looking inside the Parsing module

Page 30
Looking inside the Parsing module
Page 31
Looking inside the Parsing module
Page 32
Looking inside the Parsing module
Page 33
Looking inside the Parsing module
Page 34

What about supporting the do notation?

Page 35

Making a parsing monad

Page 36

Our parsing monad

instance Monad Parser where
  return x = P (\ s -> Just (x,s))

  P p >>= f = P (\ s -> case p s of
                          Nothing    -> Nothing
                          Just (a,r) -> parse (f a) r)
Page 37

About monads

Page 38

Summary