SlideShare a Scribd company logo
A Very Quick Tour of Parsec
For the LA Haskell User Group
Setup:
:set +m
:set -XNoMonomorphismRestriction
import Text.Parsec
import Control.Monad
Types
:i Parsec ParsecT
:i State
Escaping the Monad
:t runParser
:t runParserT
:t parse
:t parseTest
Demonstration
parseTest (char 'a') "a"
parseTest (char 'a') "ab"
parseTest (char 'a') "d"
Simple Parsers
:t oneOf
:t letter
:t digit
:t space
Do Notation
fmap f p
Parse using p and apply f to the result
p >>= q
Parse using p first, and then using q, possibly using the result
of p.
do { x ← … ; y ← … ; … }
Combine several parse results
Modifying Parsers
:t many
:t count
:t chainl
:t chainr
Parsing Phone Book Entries
let tel = do
g1 <- count 3 digit;
char '-'
g2 <- count 3 digit
char '-'
g3 <- count 4 digit
return (g1, g2, g3)
Parsing Phone Book Entries
let name = many1 letter
let fullName = do
last <- name
char ','
space
first <- name
return (first, last)
Parsing Phone Book Entries
let phoneBook = do
(first, last) <- fullName
space
char '('
(g1, g2, g3) <- tel
char ')'
return (first, last, g1, g2, g3)
Parsing Phone Book Entries
parseTest phoneBook
"Freeman, Phillip (555-555-5555)"
Combining Parsers
:t sepBy
:t (<|>)
Handling Failure
:t try
:t <?>
Handling Multiple First Names
let nameSep = try $ do
space
notFollowedBy (char '(')
let fullName = do
last <- name
char ','
space
rest <- sepBy1 name nameSep
return $ rest ++ [last]
Handling Multiple First Names
let phoneBook = do
names <- fullName
space
char '('
(g1, g2, g3) <- tel
char ')'
return (names, g1, g2, g3)
Parsing Phone Book Entries
parseTest phoneBook
"Freeman, Phillip Antony (555-555-
5555)"
User State
Parsec(T) is a state monad, so we can carry
around user state as well as the parser's internal
state.
:t getState
:t setState
:t modifyState
Example - { an
bn
| n ≥ 0 }
let
a = liftM2 (curry fst) (char 'a')
(modifyState succ)
an
bn
= do
as <- many a
n <- getState
bs <- count n $ char 'b'
eof
return $ as ++ bs
Example - { an
bn
| n ≥ 0 }
runParser an
bn
0 "" "aaabb"
runParser an
bn
0 "" "aabb"
runParser an
bn
0 "" "aabbb"
Example – Print Debugging
let
char' c = lift (print c) >> char c
chars = many $
(char' 'a') <|> (char' 'b')
runParserT chars () "" "aabb"
Expression Parsers
import Text.Parsec.Expr
:t buildExpressionParser
:i Operator OperatorTable Assoc
Example - Expression Parsers
let
number = fmap read $ many1 digit
bracket = between (char '(') (char ')') numExpr
atom = bracket <|> number
numExpr = buildExpressionParser
[ [ Infix (do { char '/'; return (/) }) AssocRight
, Infix (do { char '*'; return (*) }) AssocRight ]
, [ Infix (do { char '+'; return (+) }) AssocRight
, Infix (do { char '-'; return (-) }) AssocRight ]
, [ Prefix $ do { char '-'; return negate } ]
] atom
Example - Expression Parsers
parseText numExpr “(1+2*4)/3”
Language Definitions
import Text.Parsec.Token
import Text.Parsec.Language
:i GenLanguageDef GenTokenParser
Language Definitions
let langDef = haskellStyle -- { ... }
let parser = makeTokenParser langDef
let
stringLiteral' = stringLiteral parser
integer' = integer parser
float' = float parser
lexeme' = lexeme parser
Language Definitions
parseTest stringLiteral' ""Test""
parseTest
(lexeme' stringLiteral')
""Test" {-# Comment #-}"

More Related Content

PDF
Rcpp11 genentech
Romain Francois
 
PDF
Live in shell
Tiến Nguyễn
 
PDF
multi-line record grep
Ryoichi KATO
 
PDF
Goroutines and Channels in practice
Guilherme Garnier
 
PDF
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
Sylvain Hallé
 
PDF
Swift study: Closure
Futada Takashi
 
PDF
The Ring programming language version 1.3 book - Part 25 of 88
Mahmoud Samir Fayed
 
PDF
Writing Perl 6 Rx
lichtkind
 
Rcpp11 genentech
Romain Francois
 
Live in shell
Tiến Nguyễn
 
multi-line record grep
Ryoichi KATO
 
Goroutines and Channels in practice
Guilherme Garnier
 
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
Sylvain Hallé
 
Swift study: Closure
Futada Takashi
 
The Ring programming language version 1.3 book - Part 25 of 88
Mahmoud Samir Fayed
 
Writing Perl 6 Rx
lichtkind
 

What's hot (20)

KEY
サイ本 文
Takashi Takizawa
 
PDF
C project on a bookshop for saving of coustmer record
Zaibi Gondal
 
PDF
Vim Registers
Weverton Timoteo
 
PDF
Flux and InfluxDB 2.0
InfluxData
 
PDF
Hello Swift 3/5 - Function
Cody Yun
 
PPTX
Random numbers c++ class 11 and 12
SATHASIVAN H
 
PDF
Optimizing the Grafana Platform for Flux
InfluxData
 
ODP
2.2 higher order-functions
futurespective
 
PDF
2015.3.12 the root of lisp
Chung-Hsiang Ofa Hsueh
 
DOCX
Array using recursion
Swarup Boro
 
PDF
The Ring programming language version 1.7 book - Part 38 of 196
Mahmoud Samir Fayed
 
DOCX
Tugas Program C++
Reynes E. Tekay
 
PDF
Inc decsourcefile
heartplusbrain
 
PDF
Week7
WanSurang FK
 
PDF
Bash4
apsegundo
 
PDF
Groovy and Grails talk
desistartups
 
DOCX
Lab 1
rimshailyas1
 
PDF
Quick 入門 | iOS RDD テストフレームワーク for Swift/Objective-C
Yuki Tanabe
 
PDF
Kalman filter
COMSATS Abbottabad
 
PDF
Concurrency in Golang
Oliver N
 
サイ本 文
Takashi Takizawa
 
C project on a bookshop for saving of coustmer record
Zaibi Gondal
 
Vim Registers
Weverton Timoteo
 
Flux and InfluxDB 2.0
InfluxData
 
Hello Swift 3/5 - Function
Cody Yun
 
Random numbers c++ class 11 and 12
SATHASIVAN H
 
Optimizing the Grafana Platform for Flux
InfluxData
 
2.2 higher order-functions
futurespective
 
2015.3.12 the root of lisp
Chung-Hsiang Ofa Hsueh
 
Array using recursion
Swarup Boro
 
The Ring programming language version 1.7 book - Part 38 of 196
Mahmoud Samir Fayed
 
Tugas Program C++
Reynes E. Tekay
 
Inc decsourcefile
heartplusbrain
 
Bash4
apsegundo
 
Groovy and Grails talk
desistartups
 
Quick 入門 | iOS RDD テストフレームワーク for Swift/Objective-C
Yuki Tanabe
 
Kalman filter
COMSATS Abbottabad
 
Concurrency in Golang
Oliver N
 
Ad

Similar to Parsec (20)

PDF
TMPA-2017: Functional Parser of Markdown Language Based on Monad Combining an...
Iosif Itkin
 
PDF
Why is Haskell so hard! (And how to deal with it?)
Saurabh Nanda
 
PDF
Combinator parsing
Swanand Pagnis
 
PDF
Template Haskell
Sergey Stretovich
 
PDF
DEFUN 2008 - Real World Haskell
Bryan O'Sullivan
 
PDF
Simple JSON parser
Dongjun Lee
 
PPTX
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
PDF
An introduction on language processing
Ralf Laemmel
 
PPT
Haskell retrospective
chenge2k
 
PDF
Template Haskell Tutorial
kizzx2
 
PDF
The Art Of Parsing @ Devoxx France 2014
Dinesh Bolkensteyn
 
PDF
Real World Haskell: Lecture 1
Bryan O'Sullivan
 
PDF
Alexey Golub - Writing parsers in c# | 3Shape Meetup
Oleksii Holub
 
PDF
Certified bit coded regular expression parsing
rodrigogribeiro
 
PDF
Real World Haskell: Lecture 2
Bryan O'Sullivan
 
PPTX
Learning at the Speed of JavaScript
Jake Witcher
 
PDF
Parser combinator in swift
Vijaya Prakash Kandel
 
KEY
Programming Haskell Chapter8
Kousuke Ruichi
 
PDF
Elm: give it a try
Eugene Zharkov
 
PDF
Parser combinators
lifecoder
 
TMPA-2017: Functional Parser of Markdown Language Based on Monad Combining an...
Iosif Itkin
 
Why is Haskell so hard! (And how to deal with it?)
Saurabh Nanda
 
Combinator parsing
Swanand Pagnis
 
Template Haskell
Sergey Stretovich
 
DEFUN 2008 - Real World Haskell
Bryan O'Sullivan
 
Simple JSON parser
Dongjun Lee
 
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
An introduction on language processing
Ralf Laemmel
 
Haskell retrospective
chenge2k
 
Template Haskell Tutorial
kizzx2
 
The Art Of Parsing @ Devoxx France 2014
Dinesh Bolkensteyn
 
Real World Haskell: Lecture 1
Bryan O'Sullivan
 
Alexey Golub - Writing parsers in c# | 3Shape Meetup
Oleksii Holub
 
Certified bit coded regular expression parsing
rodrigogribeiro
 
Real World Haskell: Lecture 2
Bryan O'Sullivan
 
Learning at the Speed of JavaScript
Jake Witcher
 
Parser combinator in swift
Vijaya Prakash Kandel
 
Programming Haskell Chapter8
Kousuke Ruichi
 
Elm: give it a try
Eugene Zharkov
 
Parser combinators
lifecoder
 
Ad

Recently uploaded (20)

PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
The Future of Artificial Intelligence (AI)
Mukul
 
Software Development Methodologies in 2025
KodekX
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Doc9.....................................
SofiaCollazos
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 

Parsec

  • 1. A Very Quick Tour of Parsec For the LA Haskell User Group Setup: :set +m :set -XNoMonomorphismRestriction import Text.Parsec import Control.Monad
  • 3. Escaping the Monad :t runParser :t runParserT :t parse :t parseTest
  • 4. Demonstration parseTest (char 'a') "a" parseTest (char 'a') "ab" parseTest (char 'a') "d"
  • 5. Simple Parsers :t oneOf :t letter :t digit :t space
  • 6. Do Notation fmap f p Parse using p and apply f to the result p >>= q Parse using p first, and then using q, possibly using the result of p. do { x ← … ; y ← … ; … } Combine several parse results
  • 7. Modifying Parsers :t many :t count :t chainl :t chainr
  • 8. Parsing Phone Book Entries let tel = do g1 <- count 3 digit; char '-' g2 <- count 3 digit char '-' g3 <- count 4 digit return (g1, g2, g3)
  • 9. Parsing Phone Book Entries let name = many1 letter let fullName = do last <- name char ',' space first <- name return (first, last)
  • 10. Parsing Phone Book Entries let phoneBook = do (first, last) <- fullName space char '(' (g1, g2, g3) <- tel char ')' return (first, last, g1, g2, g3)
  • 11. Parsing Phone Book Entries parseTest phoneBook "Freeman, Phillip (555-555-5555)"
  • 14. Handling Multiple First Names let nameSep = try $ do space notFollowedBy (char '(') let fullName = do last <- name char ',' space rest <- sepBy1 name nameSep return $ rest ++ [last]
  • 15. Handling Multiple First Names let phoneBook = do names <- fullName space char '(' (g1, g2, g3) <- tel char ')' return (names, g1, g2, g3)
  • 16. Parsing Phone Book Entries parseTest phoneBook "Freeman, Phillip Antony (555-555- 5555)"
  • 17. User State Parsec(T) is a state monad, so we can carry around user state as well as the parser's internal state. :t getState :t setState :t modifyState
  • 18. Example - { an bn | n ≥ 0 } let a = liftM2 (curry fst) (char 'a') (modifyState succ) an bn = do as <- many a n <- getState bs <- count n $ char 'b' eof return $ as ++ bs
  • 19. Example - { an bn | n ≥ 0 } runParser an bn 0 "" "aaabb" runParser an bn 0 "" "aabb" runParser an bn 0 "" "aabbb"
  • 20. Example – Print Debugging let char' c = lift (print c) >> char c chars = many $ (char' 'a') <|> (char' 'b') runParserT chars () "" "aabb"
  • 21. Expression Parsers import Text.Parsec.Expr :t buildExpressionParser :i Operator OperatorTable Assoc
  • 22. Example - Expression Parsers let number = fmap read $ many1 digit bracket = between (char '(') (char ')') numExpr atom = bracket <|> number numExpr = buildExpressionParser [ [ Infix (do { char '/'; return (/) }) AssocRight , Infix (do { char '*'; return (*) }) AssocRight ] , [ Infix (do { char '+'; return (+) }) AssocRight , Infix (do { char '-'; return (-) }) AssocRight ] , [ Prefix $ do { char '-'; return negate } ] ] atom
  • 23. Example - Expression Parsers parseText numExpr “(1+2*4)/3”
  • 24. Language Definitions import Text.Parsec.Token import Text.Parsec.Language :i GenLanguageDef GenTokenParser
  • 25. Language Definitions let langDef = haskellStyle -- { ... } let parser = makeTokenParser langDef let stringLiteral' = stringLiteral parser integer' = integer parser float' = float parser lexeme' = lexeme parser
  • 26. Language Definitions parseTest stringLiteral' ""Test"" parseTest (lexeme' stringLiteral') ""Test" {-# Comment #-}"