SlideShare une entreprise Scribd logo
1  sur  30
Creating Domain Specific
       Languages in F#




          PhD student @ University of Cambridge
tomas@tomasp.net   Tomas Petricek          @tomaspetricek
         Conspirator behind http://fsharp.org
Real World Functional
                  Programming tutorials F# and C#
                  monads   functional concepts     practical examples




              industry experts F# Deep Dives
                                           .
  domain modeling      financial & insurance web & data
                  actor model   concurrency   social gaming



F# Trainings & Consulting
testing   London       async & concurrent   New York    DSLs
data processing    http://functional-programming.net
software stacks
       trainings teaching F# user groups     snippets

mac and linux   cross-platform books and tutorials
  F# Software Foundation
   F# community   open-source MonoDevelop
  http://www.fsharp.org
         contributions research support
                  consultancy mailing list
Domain-specific languages

We have a class of problems
 Create a language for the class
 Use language to solve them

DSLs and functional languages
 Internal DSLs are just library
 External DSLs are easier to build
Domain-specific languages

Language for solving specific problems

 Fun.cylinder
 |> Fun.translate (0, 0, 1)
 |> Fun.color Color.Gold $
 Fun.cone
 |> Fun.color Color.DarkRed


Contrast with general purpose languages
Demo: Building a castle

Domain Specific Language
 Defines a few simple primitives
 Extensible by composition

Single-purpose or general-purpose?
 Most code is single-purpose
 Can use general-purpose if needed

See also FAKE: the F# Make
Building a DSL for:
 Option Pricing
Demo: Modeling Euro options

What is the language?
 Primitive values
 Composition operations

How do we use the model?
 Drawing a pay-off diagram
 Calculating option price
 Checking for execution
Composed options
Building the model

Primitives of the language
    type OptionKind = Call | Put
    type Option =
      | European of OptionKind * float


Composition combinators
      | Combine of Option * Option
      | Times of float * Option
Demo: Building & using the
             DSL
Make it more convenient
  Custom operators
  Derived primitives

Use it for its purpose
  Drawing pay-off diagrams
  Evaluating option price
Domain-specific languages
Advantages                   Disadvantages
Readability                  Additional abstraction
  Greater for External DSL     Smaller for Internal DSL
Maintainability              Time to implement
  Hides the implementation     Easier for Internal DSL
  Internals can be changed   Time to learn
Domain Focus                   Avoid crazy operators
  Non-experts can read it      Make it familiar
Internal DSL: Building Blocks
Vanilla .NET           F# Specific
Method chaining        Pipelining
Enumerations           Discriminated Unions
Classes                Records
Operator Overloading   Custom Operators
Attributes             Quotations
Iterators & LINQ       Computation Expressions
Extension methods      Functions
Building a DSL for:
Detecting Price Patterns
Declining pattern
Rounding top pattern
Multiple bottom pattern
Doman-specific language approach

Primitive classifiers
  Declining price
  Rising price
Combinators for classifiers
  Average using regression
  Sequence multiple patterns
  Check patterns at the same time
Demo: Detecting price patterns
Building complex from simple
 Check multiple conditions
   let bothAnd a b =
     both a b |> map (fun (a, b) -> a && b)

 Calculate minimum value
   let minimum =
     reduce min |> map (fun v -> Math.Round(v, 2))

 All values are in a range
   let inRange min max =
     bothAnd (atLeast min) (atMost max)
How does it work?

What is a classifier?
   type Classifier<'T> =
     ClassifyFunc of ((DateTime * float)[] -> 'T)


A function value!
  Given data, calculate the result
  Generic – can produce any value
  Abstract – representation is hidden
Demo: Detecting more patterns

Double bottom pattern
  Change over regression
  Down–Up two times

Declining fast pattern
  Declining over regression
  (Max – Min) > 3 USD
Advanced Techniques
 for Embedded DSLs
Advanced Embedded DSLs
Computation expressions
  Reinterpret expression composition
  Add constructs with F# 3.0 queries

Meta-programming with quotations
  Reinterpret F# expressions

Active patterns
  More expressive pattern language
  Implementing external DSLs
Repeating patterns in DSLs

Repeating functions in DSLs
 Map: transform the produced value
   ('T -> 'R) -> Clsif<'T> -> Clsif<'R>
 Bind & return: composition of computations
   ('T -> Clsif<'R>) -> Clsif<'T> -> Clsif<'R>
   'T -> Clsif<'T>

Simplify using them? With language syntax?
F# computation expressions

Syntax for computations
  For types with certain operations
  Aka monads in Haskell

Declining fast pattern
  classify {
    let! max = P.maximum
    let! min = P.minimum
    let! upwards = P.regression P.rising
    return upwards & (abs (min - max) > 3.0) }
F# query expressions
Customize the meaning of a query
  event {
    for e in frm.MouseDown do
    pairwise into (e1, e2)
    select (e1.X - e2.X, e1.Y - e2.Y) into r
    iter (printfn "%A" r) }

Query for event processing
 Custom operators e.g. iter, select, pairwise
 Transformations, joins, merging and more
 Full power to be explored!
F# active patterns
Extending the pattern language
  match input with
  | Bracketed '*' '*' (body, rest)    -> (...)
  | Bracketed '[' ']' (body,
      Bracketed '(' ')' (link, rest)) -> (...)
  | _ -> (...)

Parsing Markdown format
 Detecting character patterns
 Detecting multi-line patterns
 See more at http://manning.com/petricek2
Summary
How To: Building your own DSL

    ❶ Understand Primitives
       and Combinators

   ❷ Model the language using
     Discriminated Unions

    ❸ Add convenient Syntax
For more information…
Learn and explore F#
 Read tutorials at http://tryfsharp.org

Join & help with F# Foundation
 Visit http://fsharp.org and for on GitHub!

New York F# Trainings & Tutorials in May
 Check out: http://functional-programming.net
 Contact me directly: tomas@tomasp.net

Contenu connexe

Tendances

IF Statement
IF StatementIF Statement
IF StatementYunis20
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animationsPratikNaik41
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationP3 InfoTech Solutions Pvt. Ltd.
 
Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiersNilimesh Halder
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Abid Kohistani
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Python Basics
Python BasicsPython Basics
Python BasicsPooja B S
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPyHuy Nguyen
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++Neeru Mittal
 

Tendances (20)

IF Statement
IF StatementIF Statement
IF Statement
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animations
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and Indentation
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiers
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python ppt
Python pptPython ppt
Python ppt
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Hashing data
Hashing dataHashing data
Hashing data
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Array in c#
Array in c#Array in c#
Array in c#
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 

En vedette

Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Tomas Petricek
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Skills Matter
 
Tame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLsTame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLsYan Cui
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Robert Pickering
 
Martial art
Martial artMartial art
Martial artgoku6759
 
Fundamentos shaolin
Fundamentos shaolinFundamentos shaolin
Fundamentos shaolindambrocisa
 
12 Jyotirlingas
12 Jyotirlingas12 Jyotirlingas
12 Jyotirlingassangita
 
Digital Humanities in East Asia
Digital Humanities in East AsiaDigital Humanities in East Asia
Digital Humanities in East AsiaAllan Cho
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014Phillip Trelford
 
12 jyotirlingas of india
12 jyotirlingas of india12 jyotirlingas of india
12 jyotirlingas of indiaParv Garg
 
Kungfu panda philosophy
Kungfu panda philosophyKungfu panda philosophy
Kungfu panda philosophyironicjoker
 
Kung fu panda learnings
Kung fu panda learningsKung fu panda learnings
Kung fu panda learningsPrashant Sree
 
9 Presentation Lessons from Kung Fu Panda
9 Presentation Lessons from Kung Fu Panda9 Presentation Lessons from Kung Fu Panda
9 Presentation Lessons from Kung Fu PandaAnuj Malhotra
 
F# in the real world (NDC)
F# in the real world (NDC)F# in the real world (NDC)
F# in the real world (NDC)Yan Cui
 

En vedette (20)

Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#
 
Tame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLsTame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLs
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
 
DSLs in JavaScript
DSLs in JavaScriptDSLs in JavaScript
DSLs in JavaScript
 
Martial art
Martial artMartial art
Martial art
 
Fundamentos shaolin
Fundamentos shaolinFundamentos shaolin
Fundamentos shaolin
 
12 Jyotirlingas
12 Jyotirlingas12 Jyotirlingas
12 Jyotirlingas
 
10 Martial Arts and Kung Fu Training Styles in China
10 Martial Arts and Kung Fu Training Styles in China10 Martial Arts and Kung Fu Training Styles in China
10 Martial Arts and Kung Fu Training Styles in China
 
Digital Humanities in East Asia
Digital Humanities in East AsiaDigital Humanities in East Asia
Digital Humanities in East Asia
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
12 jyotirlingas of india
12 jyotirlingas of india12 jyotirlingas of india
12 jyotirlingas of india
 
Kungfu panda philosophy
Kungfu panda philosophyKungfu panda philosophy
Kungfu panda philosophy
 
Kung fu punctuation
Kung fu punctuationKung fu punctuation
Kung fu punctuation
 
04. buddhist ethics
04. buddhist ethics04. buddhist ethics
04. buddhist ethics
 
Rivers of india
Rivers of indiaRivers of india
Rivers of india
 
Kung fu panda learnings
Kung fu panda learningsKung fu panda learnings
Kung fu panda learnings
 
Martial Arts
Martial ArtsMartial Arts
Martial Arts
 
9 Presentation Lessons from Kung Fu Panda
9 Presentation Lessons from Kung Fu Panda9 Presentation Lessons from Kung Fu Panda
9 Presentation Lessons from Kung Fu Panda
 
F# in the real world (NDC)
F# in the real world (NDC)F# in the real world (NDC)
F# in the real world (NDC)
 

Similaire à Creating Domain Specific Languages in F#

F# for functional enthusiasts
F# for functional enthusiastsF# for functional enthusiasts
F# for functional enthusiastsJack Fox
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010Satish Verma
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Vitaly Baum
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesEelco Visser
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introductionPeter Gfader
 
Architecting Domain-Specific Languages
Architecting Domain-Specific LanguagesArchitecting Domain-Specific Languages
Architecting Domain-Specific LanguagesMarkus Voelter
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayTomas Petricek
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataTomas Petricek
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N yearsRuslan Shevchenko
 
Chapter One
Chapter OneChapter One
Chapter Onebolovv
 
Project_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_finalProject_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_finalJerin John
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...Maarten Balliauw
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...Maarten Balliauw
 
Compiler design Introduction
Compiler design IntroductionCompiler design Introduction
Compiler design IntroductionAman Sharma
 
Building scalable and language-independent Java services using Apache Thrift ...
Building scalable and language-independent Java services using Apache Thrift ...Building scalable and language-independent Java services using Apache Thrift ...
Building scalable and language-independent Java services using Apache Thrift ...IndicThreads
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionEelco Visser
 
Programming Design Guidelines
Programming Design GuidelinesProgramming Design Guidelines
Programming Design Guidelinesintuitiv.de
 

Similaire à Creating Domain Specific Languages in F# (20)

F# for functional enthusiasts
F# for functional enthusiastsF# for functional enthusiasts
F# for functional enthusiasts
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
 
F# Tutorial @ QCon
F# Tutorial @ QConF# Tutorial @ QCon
F# Tutorial @ QCon
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
F# for Trading
F# for TradingF# for Trading
F# for Trading
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introduction
 
Architecting Domain-Specific Languages
Architecting Domain-Specific LanguagesArchitecting Domain-Specific Languages
Architecting Domain-Specific Languages
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional Way
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the Data
 
Introduction to F#
Introduction to F#Introduction to F#
Introduction to F#
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
 
Chapter One
Chapter OneChapter One
Chapter One
 
Project_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_finalProject_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_final
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
 
Compiler design Introduction
Compiler design IntroductionCompiler design Introduction
Compiler design Introduction
 
Building scalable and language-independent Java services using Apache Thrift ...
Building scalable and language-independent Java services using Apache Thrift ...Building scalable and language-independent Java services using Apache Thrift ...
Building scalable and language-independent Java services using Apache Thrift ...
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
Programming Design Guidelines
Programming Design GuidelinesProgramming Design Guidelines
Programming Design Guidelines
 

Plus de Tomas Petricek

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationTomas Petricek
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensTomas Petricek
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Tomas Petricek
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#Tomas Petricek
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleTomas Petricek
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Tomas Petricek
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in DepthTomas Petricek
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Tomas Petricek
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languagesTomas Petricek
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for HaskellTomas Petricek
 
Concurrent programming with Agents
Concurrent programming with AgentsConcurrent programming with Agents
Concurrent programming with AgentsTomas Petricek
 

Plus de Tomas Petricek (15)

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent Computation
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizens
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis Simple
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in Depth
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languages
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
 
F# on the Server-Side
F# on the Server-SideF# on the Server-Side
F# on the Server-Side
 
Teaching F#
Teaching F#Teaching F#
Teaching F#
 
F# in MonoDevelop
F# in MonoDevelopF# in MonoDevelop
F# in MonoDevelop
 
Academia
AcademiaAcademia
Academia
 
Concurrent programming with Agents
Concurrent programming with AgentsConcurrent programming with Agents
Concurrent programming with Agents
 

Creating Domain Specific Languages in F#

  • 1. Creating Domain Specific Languages in F# PhD student @ University of Cambridge tomas@tomasp.net Tomas Petricek @tomaspetricek Conspirator behind http://fsharp.org
  • 2. Real World Functional Programming tutorials F# and C# monads functional concepts practical examples industry experts F# Deep Dives . domain modeling financial & insurance web & data actor model concurrency social gaming F# Trainings & Consulting testing London async & concurrent New York DSLs data processing http://functional-programming.net
  • 3. software stacks trainings teaching F# user groups snippets mac and linux cross-platform books and tutorials F# Software Foundation F# community open-source MonoDevelop http://www.fsharp.org contributions research support consultancy mailing list
  • 4. Domain-specific languages We have a class of problems Create a language for the class Use language to solve them DSLs and functional languages Internal DSLs are just library External DSLs are easier to build
  • 5. Domain-specific languages Language for solving specific problems Fun.cylinder |> Fun.translate (0, 0, 1) |> Fun.color Color.Gold $ Fun.cone |> Fun.color Color.DarkRed Contrast with general purpose languages
  • 6. Demo: Building a castle Domain Specific Language Defines a few simple primitives Extensible by composition Single-purpose or general-purpose? Most code is single-purpose Can use general-purpose if needed See also FAKE: the F# Make
  • 7. Building a DSL for: Option Pricing
  • 8. Demo: Modeling Euro options What is the language? Primitive values Composition operations How do we use the model? Drawing a pay-off diagram Calculating option price Checking for execution
  • 10. Building the model Primitives of the language type OptionKind = Call | Put type Option = | European of OptionKind * float Composition combinators | Combine of Option * Option | Times of float * Option
  • 11. Demo: Building & using the DSL Make it more convenient Custom operators Derived primitives Use it for its purpose Drawing pay-off diagrams Evaluating option price
  • 12. Domain-specific languages Advantages Disadvantages Readability Additional abstraction Greater for External DSL Smaller for Internal DSL Maintainability Time to implement Hides the implementation Easier for Internal DSL Internals can be changed Time to learn Domain Focus Avoid crazy operators Non-experts can read it Make it familiar
  • 13. Internal DSL: Building Blocks Vanilla .NET F# Specific Method chaining Pipelining Enumerations Discriminated Unions Classes Records Operator Overloading Custom Operators Attributes Quotations Iterators & LINQ Computation Expressions Extension methods Functions
  • 14. Building a DSL for: Detecting Price Patterns
  • 18. Doman-specific language approach Primitive classifiers Declining price Rising price Combinators for classifiers Average using regression Sequence multiple patterns Check patterns at the same time
  • 19. Demo: Detecting price patterns Building complex from simple Check multiple conditions let bothAnd a b = both a b |> map (fun (a, b) -> a && b) Calculate minimum value let minimum = reduce min |> map (fun v -> Math.Round(v, 2)) All values are in a range let inRange min max = bothAnd (atLeast min) (atMost max)
  • 20. How does it work? What is a classifier? type Classifier<'T> = ClassifyFunc of ((DateTime * float)[] -> 'T) A function value! Given data, calculate the result Generic – can produce any value Abstract – representation is hidden
  • 21. Demo: Detecting more patterns Double bottom pattern Change over regression Down–Up two times Declining fast pattern Declining over regression (Max – Min) > 3 USD
  • 22. Advanced Techniques for Embedded DSLs
  • 23. Advanced Embedded DSLs Computation expressions Reinterpret expression composition Add constructs with F# 3.0 queries Meta-programming with quotations Reinterpret F# expressions Active patterns More expressive pattern language Implementing external DSLs
  • 24. Repeating patterns in DSLs Repeating functions in DSLs Map: transform the produced value ('T -> 'R) -> Clsif<'T> -> Clsif<'R> Bind & return: composition of computations ('T -> Clsif<'R>) -> Clsif<'T> -> Clsif<'R> 'T -> Clsif<'T> Simplify using them? With language syntax?
  • 25. F# computation expressions Syntax for computations For types with certain operations Aka monads in Haskell Declining fast pattern classify { let! max = P.maximum let! min = P.minimum let! upwards = P.regression P.rising return upwards & (abs (min - max) > 3.0) }
  • 26. F# query expressions Customize the meaning of a query event { for e in frm.MouseDown do pairwise into (e1, e2) select (e1.X - e2.X, e1.Y - e2.Y) into r iter (printfn "%A" r) } Query for event processing Custom operators e.g. iter, select, pairwise Transformations, joins, merging and more Full power to be explored!
  • 27. F# active patterns Extending the pattern language match input with | Bracketed '*' '*' (body, rest) -> (...) | Bracketed '[' ']' (body, Bracketed '(' ')' (link, rest)) -> (...) | _ -> (...) Parsing Markdown format Detecting character patterns Detecting multi-line patterns See more at http://manning.com/petricek2
  • 29. How To: Building your own DSL ❶ Understand Primitives and Combinators ❷ Model the language using Discriminated Unions ❸ Add convenient Syntax
  • 30. For more information… Learn and explore F# Read tutorials at http://tryfsharp.org Join & help with F# Foundation Visit http://fsharp.org and for on GitHub! New York F# Trainings & Tutorials in May Check out: http://functional-programming.net Contact me directly: tomas@tomasp.net

Notes de l'éditeur

  1. Prefer internal DSLs