SlideShare a Scribd company logo
1 of 30
FPARSEC HANDS ON
Phillip Trelford
F#unctional Londoners,
2014
INTERNAL DSLS - EXAMPLES
Fake
#r "tools/FAKE/tools/FakeLib.dll"
open Fake
Target "Test" (fun _ ->
trace "Testing stuff..."
)
Target "Deploy" (fun _ ->
trace "Heavy deploy action"
)
"Test" // define the dependencies
==> "Deploy"
Run "Deploy"
Canopy
"starting a game of 2048" &&& fun _ ->
start firefox
url "http://gabrielecirulli.github.io/2048/"
let score = element ".score-container"
printfn "Score %s" score.Text
while not(lost()) && not (won()) do
press up
press right
press left
press up
EXTERNAL DSLS IN ACTION
1. Domain-specific syntax
2. Proprietary encodings
3. Custom execution
environments
BUILDING EXTERNAL DSLS
Abstract Syntax Tree (AST)
Parse
Execute
PARSING OPTIONS
Hand rolled
•Regex
•Active
Patterns
FParsec
•Combinators
•Monadic
FsLex, FsYacc
•Lexer
•Parser
FPARSEC
FParsec Hands On
F#unctional Londoners
2014
THINGS YOU SHOULD NEVER DO
Custom Operators
Funny picture
FUNSCRIPT’S TYPESCRIPT PARSER
FParsec
let interfaceDeclaration =
str_ws "interface" >>. identifier .>>. typeParams
.>>. interfaceExtendsClause .>>. objectType
|>> fun (((id, tps), ex), t) ->
InterfaceDeclaration(id, tps, ex, t)
TypeScript Definition
interface JQueryKeyEventObject
extends JQueryInputEventObject {
char: any;
charCode: number;
key: any;
keyCode: number;
}
FPARSEC TUTORIAL
open FParsec
let test p str =
match run p str with
| Success(result, _, _) -> printfn "Success: %A" result
| Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg
test pfloat "1.25"
test pfloat "1.25E 2"
let str s = pstring s
let floatBetweenBrackets = str "[" >>. pfloat .>> str "]"
test floatBetweenBrackets "[1.0]"
test floatBetweenBrackets "[]"
test floatBetweenBrackets "[1.0]"
PARSING OPERATORS
// we set up an operator precedence parser for parsing the arithmetic expressions
let opp = new OperatorPrecedenceParser<float,unit,unit>()
let expr = opp.ExpressionParser
opp.TermParser <- number <|> between (str_ws "(") (str_ws ")") expr
// operator definitions follow the schema
// operator type, string, trailing whitespace parser, precedence, associativity, function to apply
opp.AddOperator(InfixOperator("+", ws, 1, Associativity.Left, (+)))
opp.AddOperator(InfixOperator("-", ws, 1, Associativity.Left, (-)))
opp.AddOperator(InfixOperator("*", ws, 2, Associativity.Left, (*)))
opp.AddOperator(InfixOperator("/", ws, 2, Associativity.Left, (/)))
opp.AddOperator(InfixOperator("^", ws, 3, Associativity.Right, fun x y -> System.Math.Pow(x, y)))
opp.AddOperator(PrefixOperator("-", ws, 4, true, fun x -> -x))
TURTLES ALL THE WAY
DOWN
FParsec Hands On
F#unctional Londoners
2014
TURTLE LANGUAGE
repeat 10
[right 36 repeat 5
[forward 54 right 72]]
TURTLE AST
module AST
type arg = int
type command =
| Forward of arg
| Turn of arg
| Repeat of arg * command list
TURTLE PARSER: FORWARD AND
TURN
open AST
open FParsec
let pforward =
pstring "forward" >>. spaces1 >>. pfloat
|>> fun x -> Forward(int x)
let pleft =
pstring "left" >>. spaces1 >>. pfloat
|>> fun x -> Turn(int -x)
let pright =
pstring "right" >>. spaces1 >>. pfloat
|>> fun x -> Turn(int x)
TURTLE PARSER: REPEAT
COMMAND
let pcommand = pforward <|> pleft <|> pright
let block = between (pstring "[") (pstring "]") (many1 (pcommand .>> spaces))
let prepeat =
pstring "repeat" >>. spaces1 >>. pfloat .>> spaces .>>. block
|>> fun (n,commands) -> Repeat(int n, commands)
TURTLE PARSER: FORWARD
REPEAT
let prepeat, prepeatimpl = createParserForwardedToRef ()
let pcommand = pforward <|> pleft <|> pright <|> prepeat
let block = between (pstring "[") (pstring "]") (many1 (pcommand .>> spaces))
prepeatimpl :=
pstring "repeat" >>. spaces1 >>. pfloat .>> spaces .>>. block
|>> fun (n,commands) -> Repeat(int n, commands)
TURTLE INTERPRETER: PATTERN
MATCHING
let rec perform turtle = function
| Forward n ->
let r = float turtle.A * Math.PI / 180.0
let dx, dy = float n * cos r, float n * sin r
let x, y = turtle.X, turtle.Y
let x',y' = x + dx, y + dy
drawLine (x,y) (x',y')
{ turtle with X = x'; Y = y' }
| Turn n -> { turtle with A = turtle.A + n }
| Repeat (n, commands) ->
let rec repeat turtle = function
| 0 -> turtle
| n -> repeat (performAll turtle commands) (n-1)
repeat turtle n
and performAll = List.fold perform
TURTLE: PROCEDURES
to square
repeat 4 [forward 50 right 90]
end
to flower
repeat 36 [right 10 square]
end
to garden
repeat 25 [set-random-position flower]
end
garden
SMALL BASIC COMPILER
FParsec Hands On
F#unctional Londoners
2014
SMALL BASIC IDE
FParsec Hands On
F#unctional Londoners
2014
SMALL BASIC
SAMPLE
Sub Init
gw = 598
gh = 428
GraphicsWindow.BackgroundColor =
"DodgerBlue"
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
color = "1=Orange;2=Cyan;3=Lime;"
size = "1=20;2=16;3=12;"
passed = 0
cd = "False" ' collision detected
EndSub
SMALL BASIC AST
/// Small Basic expression
type expr =
| Literal of value
| Identifier of identifier
| GetAt of location
| Func of invoke
| Neg of expr
| Arithmetic of expr * arithmetic * expr
| Comparison of expr * comparison * expr
| Logical of expr * logical * expr
/// Small Basic instruction
type instruction =
| Assign of assign
| SetAt of location * expr
| PropertySet of string * string * expr
| Action of invoke
| For of assign * expr * expr
| EndFor
| If of expr
| ElseIf of expr
| Else
| EndIf
| While of expr
| EndWhile
| Sub of identifier * string list
| EndSub
| Label of label
| Goto of label
SMALL BASIC PARSER
/// > For i = 1 To 100 Step 2
let pfor =
let pfrom = str_ws1 "For" >>. pset
let pto = str_ws1 "To" >>. pexpr
let pstep = str_ws1 "Step" >>. pexpr
let toStep = function None -> Literal(Int(1)) | Some s -> s
pipe3 pfrom pto (opt pstep) (fun f t s -> For(f, t, toStep s))
let pendfor = str_ws "EndFor" |>> (fun _ -> EndFor)
SMALL BASIC COMPILER: GOTO
| Goto(name) ->
let label = obtainLabel il name
il.Emit(OpCodes.Br, label)
| Label(name) ->
let label = obtainLabel il name
il.MarkLabel(label)
RESOURCES
FParsec Hands On
F#unctional Londoners
2014
F# KOANS
[<Koan>]
let SquareEvenNumbersWithPipelineOperator() =
(* In F#, you can use the pipeline operator to get the benefit of
the parens style with the readability of the statement style. *)
let result =
[0..5]
|> List.filter isEven
|> List.map square
AssertEquality result __
TRYFSHARP.ORG
F# BOOKS
QUESTIONS
Twitter: @ptrelford
Blog: http://trelford.com/blog
Turtle: http://fssnip.net/nN

More Related Content

What's hot

Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehmanNauman Rehman
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with PythonHan Lee
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 

What's hot (20)

Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Swift 2
Swift 2Swift 2
Swift 2
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Python programming
Python  programmingPython  programming
Python programming
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 

Similar to FParsec Hands On - F#unctional Londoners 2014

Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015Phillip Trelford
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of RubyTom Crinson
 
Discover Dart(lang) - Meetup 07/12/2016
Discover Dart(lang) - Meetup 07/12/2016Discover Dart(lang) - Meetup 07/12/2016
Discover Dart(lang) - Meetup 07/12/2016Stéphane Este-Gracias
 
Using browser() in R
Using browser() in RUsing browser() in R
Using browser() in RLeon Kim
 
Reasonable Code With Fsharp
Reasonable Code With FsharpReasonable Code With Fsharp
Reasonable Code With FsharpMichael Falanga
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a MomentSergio Gil
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Tudor Girba
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsagniklal
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascriptReece Carlson
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 

Similar to FParsec Hands On - F#unctional Londoners 2014 (20)

Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 
Discover Dart - Meetup 15/02/2017
Discover Dart - Meetup 15/02/2017Discover Dart - Meetup 15/02/2017
Discover Dart - Meetup 15/02/2017
 
Discover Dart(lang) - Meetup 07/12/2016
Discover Dart(lang) - Meetup 07/12/2016Discover Dart(lang) - Meetup 07/12/2016
Discover Dart(lang) - Meetup 07/12/2016
 
Using browser() in R
Using browser() in RUsing browser() in R
Using browser() in R
 
Reasonable Code With Fsharp
Reasonable Code With FsharpReasonable Code With Fsharp
Reasonable Code With Fsharp
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Elixir cheatsheet
Elixir cheatsheetElixir cheatsheet
Elixir cheatsheet
 
Rust Intro
Rust IntroRust Intro
Rust Intro
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Rakudo
RakudoRakudo
Rakudo
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
ssh.isdn.test
ssh.isdn.testssh.isdn.test
ssh.isdn.test
 

More from Phillip Trelford

How to be a rock star developer
How to be a rock star developerHow to be a rock star developer
How to be a rock star developerPhillip Trelford
 
FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015Phillip Trelford
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Phillip Trelford
 
F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015Phillip Trelford
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Phillip Trelford
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015Phillip Trelford
 
Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Phillip Trelford
 
Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Phillip Trelford
 
FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015Phillip Trelford
 
Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Phillip Trelford
 
F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015Phillip Trelford
 
F# for C# devs - Leeds Sharp 2015
F# for C# devs -  Leeds Sharp 2015F# for C# devs -  Leeds Sharp 2015
F# for C# devs - Leeds Sharp 2015Phillip Trelford
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015Phillip Trelford
 
Machine learning from disaster - GL.Net 2015
Machine learning from disaster  - GL.Net 2015Machine learning from disaster  - GL.Net 2015
Machine learning from disaster - GL.Net 2015Phillip Trelford
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014Phillip Trelford
 

More from Phillip Trelford (20)

How to be a rock star developer
How to be a rock star developerHow to be a rock star developer
How to be a rock star developer
 
Mobile F#un
Mobile F#unMobile F#un
Mobile F#un
 
F# eXchange Keynote 2016
F# eXchange Keynote 2016F# eXchange Keynote 2016
F# eXchange Keynote 2016
 
FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015
 
F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015
 
Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015
 
Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015
 
FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015
 
Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015
 
F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015
 
F# for C# devs - Leeds Sharp 2015
F# for C# devs -  Leeds Sharp 2015F# for C# devs -  Leeds Sharp 2015
F# for C# devs - Leeds Sharp 2015
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015
 
Real World F# - SDD 2015
Real World F# -  SDD 2015Real World F# -  SDD 2015
Real World F# - SDD 2015
 
F# for C# devs - SDD 2015
F# for C# devs - SDD 2015F# for C# devs - SDD 2015
F# for C# devs - SDD 2015
 
Machine learning from disaster - GL.Net 2015
Machine learning from disaster  - GL.Net 2015Machine learning from disaster  - GL.Net 2015
Machine learning from disaster - GL.Net 2015
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014
 
F# in your pipe
F# in your pipeF# in your pipe
F# in your pipe
 

Recently uploaded

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 

Recently uploaded (20)

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 

FParsec Hands On - F#unctional Londoners 2014

  • 1. FPARSEC HANDS ON Phillip Trelford F#unctional Londoners, 2014
  • 2.
  • 3. INTERNAL DSLS - EXAMPLES Fake #r "tools/FAKE/tools/FakeLib.dll" open Fake Target "Test" (fun _ -> trace "Testing stuff..." ) Target "Deploy" (fun _ -> trace "Heavy deploy action" ) "Test" // define the dependencies ==> "Deploy" Run "Deploy" Canopy "starting a game of 2048" &&& fun _ -> start firefox url "http://gabrielecirulli.github.io/2048/" let score = element ".score-container" printfn "Score %s" score.Text while not(lost()) && not (won()) do press up press right press left press up
  • 4. EXTERNAL DSLS IN ACTION 1. Domain-specific syntax 2. Proprietary encodings 3. Custom execution environments
  • 5. BUILDING EXTERNAL DSLS Abstract Syntax Tree (AST) Parse Execute
  • 8. THINGS YOU SHOULD NEVER DO Custom Operators Funny picture
  • 9. FUNSCRIPT’S TYPESCRIPT PARSER FParsec let interfaceDeclaration = str_ws "interface" >>. identifier .>>. typeParams .>>. interfaceExtendsClause .>>. objectType |>> fun (((id, tps), ex), t) -> InterfaceDeclaration(id, tps, ex, t) TypeScript Definition interface JQueryKeyEventObject extends JQueryInputEventObject { char: any; charCode: number; key: any; keyCode: number; }
  • 10. FPARSEC TUTORIAL open FParsec let test p str = match run p str with | Success(result, _, _) -> printfn "Success: %A" result | Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg test pfloat "1.25" test pfloat "1.25E 2" let str s = pstring s let floatBetweenBrackets = str "[" >>. pfloat .>> str "]" test floatBetweenBrackets "[1.0]" test floatBetweenBrackets "[]" test floatBetweenBrackets "[1.0]"
  • 11. PARSING OPERATORS // we set up an operator precedence parser for parsing the arithmetic expressions let opp = new OperatorPrecedenceParser<float,unit,unit>() let expr = opp.ExpressionParser opp.TermParser <- number <|> between (str_ws "(") (str_ws ")") expr // operator definitions follow the schema // operator type, string, trailing whitespace parser, precedence, associativity, function to apply opp.AddOperator(InfixOperator("+", ws, 1, Associativity.Left, (+))) opp.AddOperator(InfixOperator("-", ws, 1, Associativity.Left, (-))) opp.AddOperator(InfixOperator("*", ws, 2, Associativity.Left, (*))) opp.AddOperator(InfixOperator("/", ws, 2, Associativity.Left, (/))) opp.AddOperator(InfixOperator("^", ws, 3, Associativity.Right, fun x y -> System.Math.Pow(x, y))) opp.AddOperator(PrefixOperator("-", ws, 4, true, fun x -> -x))
  • 12. TURTLES ALL THE WAY DOWN FParsec Hands On F#unctional Londoners 2014
  • 13. TURTLE LANGUAGE repeat 10 [right 36 repeat 5 [forward 54 right 72]]
  • 14. TURTLE AST module AST type arg = int type command = | Forward of arg | Turn of arg | Repeat of arg * command list
  • 15. TURTLE PARSER: FORWARD AND TURN open AST open FParsec let pforward = pstring "forward" >>. spaces1 >>. pfloat |>> fun x -> Forward(int x) let pleft = pstring "left" >>. spaces1 >>. pfloat |>> fun x -> Turn(int -x) let pright = pstring "right" >>. spaces1 >>. pfloat |>> fun x -> Turn(int x)
  • 16. TURTLE PARSER: REPEAT COMMAND let pcommand = pforward <|> pleft <|> pright let block = between (pstring "[") (pstring "]") (many1 (pcommand .>> spaces)) let prepeat = pstring "repeat" >>. spaces1 >>. pfloat .>> spaces .>>. block |>> fun (n,commands) -> Repeat(int n, commands)
  • 17. TURTLE PARSER: FORWARD REPEAT let prepeat, prepeatimpl = createParserForwardedToRef () let pcommand = pforward <|> pleft <|> pright <|> prepeat let block = between (pstring "[") (pstring "]") (many1 (pcommand .>> spaces)) prepeatimpl := pstring "repeat" >>. spaces1 >>. pfloat .>> spaces .>>. block |>> fun (n,commands) -> Repeat(int n, commands)
  • 18. TURTLE INTERPRETER: PATTERN MATCHING let rec perform turtle = function | Forward n -> let r = float turtle.A * Math.PI / 180.0 let dx, dy = float n * cos r, float n * sin r let x, y = turtle.X, turtle.Y let x',y' = x + dx, y + dy drawLine (x,y) (x',y') { turtle with X = x'; Y = y' } | Turn n -> { turtle with A = turtle.A + n } | Repeat (n, commands) -> let rec repeat turtle = function | 0 -> turtle | n -> repeat (performAll turtle commands) (n-1) repeat turtle n and performAll = List.fold perform
  • 19. TURTLE: PROCEDURES to square repeat 4 [forward 50 right 90] end to flower repeat 36 [right 10 square] end to garden repeat 25 [set-random-position flower] end garden
  • 20. SMALL BASIC COMPILER FParsec Hands On F#unctional Londoners 2014
  • 21. SMALL BASIC IDE FParsec Hands On F#unctional Londoners 2014
  • 22. SMALL BASIC SAMPLE Sub Init gw = 598 gh = 428 GraphicsWindow.BackgroundColor = "DodgerBlue" GraphicsWindow.Width = gw GraphicsWindow.Height = gh color = "1=Orange;2=Cyan;3=Lime;" size = "1=20;2=16;3=12;" passed = 0 cd = "False" ' collision detected EndSub
  • 23. SMALL BASIC AST /// Small Basic expression type expr = | Literal of value | Identifier of identifier | GetAt of location | Func of invoke | Neg of expr | Arithmetic of expr * arithmetic * expr | Comparison of expr * comparison * expr | Logical of expr * logical * expr /// Small Basic instruction type instruction = | Assign of assign | SetAt of location * expr | PropertySet of string * string * expr | Action of invoke | For of assign * expr * expr | EndFor | If of expr | ElseIf of expr | Else | EndIf | While of expr | EndWhile | Sub of identifier * string list | EndSub | Label of label | Goto of label
  • 24. SMALL BASIC PARSER /// > For i = 1 To 100 Step 2 let pfor = let pfrom = str_ws1 "For" >>. pset let pto = str_ws1 "To" >>. pexpr let pstep = str_ws1 "Step" >>. pexpr let toStep = function None -> Literal(Int(1)) | Some s -> s pipe3 pfrom pto (opt pstep) (fun f t s -> For(f, t, toStep s)) let pendfor = str_ws "EndFor" |>> (fun _ -> EndFor)
  • 25. SMALL BASIC COMPILER: GOTO | Goto(name) -> let label = obtainLabel il name il.Emit(OpCodes.Br, label) | Label(name) -> let label = obtainLabel il name il.MarkLabel(label)
  • 27. F# KOANS [<Koan>] let SquareEvenNumbersWithPipelineOperator() = (* In F#, you can use the pipeline operator to get the benefit of the parens style with the readability of the statement style. *) let result = [0..5] |> List.filter isEven |> List.map square AssertEquality result __

Editor's Notes

  1. http://www.quanttec.com/fparsec/about/fparsec-vs-alternatives.html https://bitbucket.org/fparsec/main/src/c234349e7b738e09a1b9eb53f5f1ef77d584f09b/Samples/Tutorial/tutorial.fs?at=default
  2. https://twitter.com/ptrelford/status/444399378217062400
  3. http://fsharp.github.io/FAKE/ http://lefthandedgoat.github.io/canopy/
  4. http://fsprojects.github.io/FsLexYacc/
  5. https://github.com/ZachBray/FunScript/blob/master/src/extra/FunScript.TypeScript/Parser.fs https://github.com/borisyankov/DefinitelyTyped/blob/master/jquery/jquery.d.ts
  6. https://bitbucket.org/fparsec/main/src/c234349e7b738e09a1b9eb53f5f1ef77d584f09b/Samples/Tutorial/tutorial.fs?at=default
  7. https://bitbucket.org/fparsec/main/src/c234349e7b738e09a1b9eb53f5f1ef77d584f09b/Samples/Calculator/calculator.fs?at=default
  8. http://fssnip.net/nM
  9. http://blogs.msdn.com/b/smallbasic/archive/2014/08/11/small-basic-game-programming-vertical-scrolling-game.aspx
  10. http://fssnip.net/nN
  11. https://bitbucket.org/ptrelford/smallbasiccompiler
  12. http://trelford.com/blog/post/fart.aspx
  13. http://blogs.msdn.com/b/smallbasic/archive/2014/08/11/small-basic-game-programming-vertical-scrolling-game.aspx