SlideShare a Scribd company logo
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 rehman
Nauman Rehman
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
Scott Wlaschin
 
Swift 2
Swift 2Swift 2
Swift 2
Jens Ravens
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Giuseppe 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 API
Mario Fusco
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
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
Adam Getchell
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
Garth 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 Fu
climatewarrior
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
rohassanie
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Hugo Firth
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
Hermann 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 2015
Phillip 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, MyHeritage
DroidConTLV
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
Tom Crinson
 
Discover Dart - Meetup 15/02/2017
Discover Dart - Meetup 15/02/2017Discover Dart - Meetup 15/02/2017
Discover Dart - Meetup 15/02/2017
Stéphane Este-Gracias
 
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
Stéphane Este-Gracias
 
Using browser() in R
Using browser() in RUsing browser() in R
Using browser() in R
Leon Kim
 
Reasonable Code With Fsharp
Reasonable Code With FsharpReasonable Code With Fsharp
Reasonable Code With Fsharp
Michael Falanga
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
Sergio Gil
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
Astrails
 
Elixir cheatsheet
Elixir cheatsheetElixir cheatsheet
Elixir cheatsheet
Héla Ben Khalfallah
 
Rust Intro
Rust IntroRust Intro
Rust Intro
Arthur Gavkaluk
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
Veera Pendyala
 
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
Tudor Girba
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
bleis tift
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
Rakudo
RakudoRakudo
Rakudo
awwaiid
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
Reece Carlson
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
ssh.isdn.test
ssh.isdn.testssh.isdn.test
ssh.isdn.test
Chris Hallman
 

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 developer
Phillip Trelford
 
Mobile F#un
Mobile F#unMobile F#un
Mobile F#un
Phillip Trelford
 
F# eXchange Keynote 2016
F# eXchange Keynote 2016F# eXchange Keynote 2016
F# eXchange Keynote 2016
Phillip 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 2015
Phillip Trelford
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015
Phillip 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 2015
Phillip Trelford
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015
Phillip Trelford
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015
Phillip 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 2015
Phillip 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 2015
Phillip 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 2015
Phillip 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 2015
Phillip 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 2015
Phillip 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 2015
Phillip Trelford
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015
Phillip Trelford
 
Real World F# - SDD 2015
Real World F# -  SDD 2015Real World F# -  SDD 2015
Real World F# - SDD 2015
Phillip Trelford
 
F# for C# devs - SDD 2015
F# for C# devs - SDD 2015F# for C# devs - SDD 2015
F# for C# devs - SDD 2015
Phillip 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 2015
Phillip Trelford
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014
Phillip Trelford
 
F# in your pipe
F# in your pipeF# in your pipe
F# in your pipe
Phillip 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

How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
Zycus
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
kalichargn70th171
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
mohitd6
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
Softradix Technologies
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
manji sharman06
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
Michał Kurzeja
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual PerfectionBuilding the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Applitools
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
Folding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a seriesFolding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a series
Philip Schwarz
 
Folding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a seriesFolding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a series
Philip Schwarz
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
kalichargn70th171
 
What’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 UpdateWhat’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 Update
VictoriaMetrics
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 

Recently uploaded (20)

How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual PerfectionBuilding the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
Folding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a seriesFolding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a series
 
Folding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a seriesFolding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a series
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
 
What’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 UpdateWhat’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 Update
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 

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