SlideShare a Scribd company logo
1 of 56
Functional Parsing
with FParsec
A parser is an application or script
that takes in data, usually in the
form of text or a stream, and
produces a data structure to
represent syntactical relationship.
string input
“(419)-423-2781”
data structure output
{ AreaCode = 419
Prefix = 423
LineNumber = 2781 }
A parser combinator is a higher
order function that takes in two
or more parsers and combines
them to make a new parser
string input
“423-2781”
let pprefix = pint32
let pprefix = pint32
let plinenumber = pint32
let pdash = pchar ‘-’
let pprefix = pint32
let plinenumber = pint32
let pdash = pchar ‘-’
let pphonenumber =
pprefix .>> pdash .>>. plinenumber
let pphonenumber =
pprefix .>> pdash .>>. plinenumber
let pphonenumber =
pprefix .>> pdash .>>. plinenumber
let pphonenumber =
pprefix_and_pdash .>>. plinenumber
let pphonenumber =
pprefix .>> pdash .>>. plinenumber
string input
“423-2781”
data structure output
(423, 2781)
string input
“(419)-423-2781”
data structure output
{ AreaCode = 419
Prefix = 423
LineNumber = 2781 }
type PhoneNumber =
{ AreaCode : int
Prefix : int
LineNumber : int }
let createPhoneNumber a p l =
{ AreaCode = a
Prefix = p
LineNumber = l }
let popenparens = pchar ‘(‘
let pcloseparens = pchar ‘)’
let pareacode =
popenparens >>. pint32 .>> pcloseparens
let pareacode =
between popenparens pcloseparens pint32
let pdash = pchar ‘-’
let pareacode =
between popenparens pcloseparens pint32 .>> pdash
let pprefix = pint32 .>> pdash
let plinenumber = pint32
let pphonenumber =
pipe3 pareacode
pprefix
plinenumber
createPhoneNumber
string input
“(419)-423-2781” OR “419-423-2781”
data structure output
{ AreaCode = 419
Prefix = 423
LineNumber = 2781 }
let A_and_B = pchar ‘A‘ .>>. pchar ‘B’
let A_and_B = pchar ‘A‘ .>>. pchar ‘B’
let A_or_B = pchar ‘A‘ <|> pchar ‘B’
let pareacode =
between popenparens pcloseparens pint32
<|> pint32 .>> pdash
How do you actually
run a parser against
input?
type Parser<’TResult, ‘TUserState> =
CharStream<‘TUserState> -> Reply<’TResult>
type Parser<’TResult, ‘TUserState> =
CharStream<‘TUserState> -> Reply<’TResult>
val run:
Parser<’a, unit> -> string -> ParserResult<’a,
unit>
type Parser<’TResult, ‘TUserState> =
CharStream<‘TUserState> -> Reply<’TResult>
val run:
Parser<’a, unit> -> string -> ParserResult<’a,
unit>
type ParserResult<’Result, ‘UserState> =
| Success of ’Result * ‘UserState * Position
| Failure of string * ParserError * ‘UserState
let test p str =
match run p str with
| Success(result, state, pos) -> ...
| Failure(errMsg, error, state) -> ...
let test p str =
match run p str with
| Success(result, _, _) ->
printfn “Success: %A” result
| Failure(errMsg, _, _) ->
printfn “Failure: %s” errMsg
runParserOnString parser
UserState.Default
“Name for the stream”
“Input string”
runParserOnStream parser
UserState.Default
“Name for the stream”
stream
Encoding.UTF8
How do you parse one
of several possible
types?
type State = OH | KY | IN | TN
type StreetAddress =
{ Street : int * string
City : string
State : State
Zipecode : int }
let createStreetAddress str c st zip =
{ Street = str
City = c
State = st
Zipcode = zip }
let isStreetName c = isLetter c || isAnyOf “ .” c
let pcomma = pchar ‘,‘ .>> spaces
let pstreet =
pint32
.>> spaces
.>>. (manySatisfy isStreetName)
.>> pcomma
|> attempt
let pcity = manySatisfy isLetter .>> pcomma
let pstate =
choice
[ stringReturn “OH” OH
stringReturn “KY” KY
stringReturn “IN” IN
stringReturn “TN” TN ]
.>> spaces
let pzipcode = pint32
let paddress =
pipe4 pstreet
pcity
pstate
pzipcode
createStreetAddress
string input
“(419)-423-2781
129 Pineview Dr., Indianapolis, IN 40118
512 Kirk Dr., Columbus, OH 54778
7009 Elm St., Lexington, KY 89776
657-322-6578
(513)-277-9856”
type ContactInfo =
| Phone of PhoneNumber
| Address of StreetAddress
let pphonenumber =
pipe3 pareacode
pprefix
plinenumber
createPhoneNumber
|>> Phone
let paddress =
pipe4 pstreet
pcity
pstate
pzipcode
createStreetAddress
|>> Address
let pcontactinfo =
[ paddress .>> spaces
pphonenumber .>> spaces ]
|> choice
|> many
Using
UserState
runParserOnString parser
UserState.Default
“Name for the stream”
“Input string”
type UserState =
{ PhoneCount: int
AddressCount: int }
with
static member Default =
{ PhoneCount = 0
AddressCount = 0 }
let incrementPhoneNumber =
let incrementPhone us =
{ us with PhoneCount = us.PhoneCount + 1 }
updateUserState incrementPhone
let incrementPhoneNumber =
let incrementPhone us =
{ us with PhoneCount = us.PhoneCount + 1 }
updateUserState incrementPhone
let incrementStreetAddress =
let incrementAddress us =
{ us with AddressCount = us.AddressCount + 1 }
updateUserState incrementPhone
let pcontactinfo =
[ paddress .>> incrementStreetAddress .>> spaces
phonenumber .>> incrementPhoneNumber .>> spaces ]
|> choice
|> many
Getting started with
FParsec
● Download the .NetCore SDK
● Create a directory for your parser scripts
● While in the directory, download Paket *
*(Paket is an alternative solution to package management in dotnet)
● Run the dotnet paket init command
● Add nuget FParsec to the paket.dependencies
file created by paket
● Run dotnet paket install
● Run dotnet paket generate-load-scripts
Alternatively, you can add generate_load_scripts: true
at the top of your paket.dependencies file before
running dotnet paket install which will automatically
generate the load scripts.
● Create an F# script file in the parent directory of
your project (ex. parsers.fsx)
● At the top of the file add the following code to
load the dll references for FParsec and open the
FParsec namespace
#load @”.paketloadnetcoreapp3.0main.group.fsx”
open FParsec

More Related Content

Recently uploaded

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdf
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 

Featured

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 

Functional Parsing with FParsec