SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

Último

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Último (20)

Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 

Destacado

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)
 

Destacado (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