SlideShare uma empresa Scribd logo
1 de 28
F# Quotations:
“Code as Data”
Jack Pappas
Dmitry Morozov
SkillsMatter Progressive F# Tutorials NYC
September 19th, 2013
Code as Data
• Code & Data – What is the difference?
• Is there a difference?
• Programs exist to process data
– The F# compiler processes data (your source
code)
• Source code is no different than other kinds of
data
This Session
• What is a “quoted expression”?
– A simple, immutable data structure
– Represents a fragment of F# code
• Syllabus
– Background
– Working with Quotations
– Manipulating Quotations
– Applications of Quotations
Background
• The idea of treating code as data first
appeared in Lisp
Lisp F#
Code (1 2 3) [1; 2; 3]
Code as Data ‘(1 2 3) <@ [1; 2; 3] @>
Background
• A language that has the natural ability to
manipulate itself is extremely powerful
• “Amplify” a developer’s productivity using
metaprogramming techniques
Background
• Other languages can manipulate their own
code
– clang: C++ program, manipulates C++
– Roslyn: C# library, manipulates C#
– f2c: C program, manipulates FORTRAN and C
• What makes Lisp and F# different?
– Reflective meta-programming
– Built-in language feature vs. external
functionality
Background
• Now that we can manipulate code as data,
what can we do with it?
• Transform
– modify, convert, translate
• Analyze
– Static analysis
– Advanced testing techniques (e.g., verification)
– Collect and record code metrics (e.g., complexity)
Background
• Execute
– Interpret the code/data
– Translate to another lang., compile, execute
– Specialized hardware (e.g., GPU, FPGA)
– Specialized execution (e.g., auto-parallelization)
– Execute remotely (e.g., web service)
– Some combination of the above
– (Rarely) execute in same context, e.g., by
translating to IL and executing
Use Cases
• LINQ support in F#
– Extension of this idea:
Cheney, Lindley, Wadler.
“The essence of language-integrated query”
• Use as an IL when developing type providers
– Quotations much easier to work with
– Create quotations, translate to IL
Use Cases
• Testing
– Moq/Foq/Unquote
• GPU programming
– Compute: FSCL, QuantAlea
– Graphics: SharpShaders (F# -> HLSL)
• Web Development (F# -> JavaScript)
– WebSharper
– FunScript
– PitFw
Comparing Alternatives
• What alternatives exist to quotations?
– F# AST
– LINQ Expression Trees
– CIL (MSIL)
• Imperative: Expression Trees, CIL
– C# lambdas compiled into Expression Trees by
the C# compiler
• Functional: F# AST, Quotations
Comparing Alternatives
• F# AST
– Designed for the compiler’s internal use
– Carries more information than quotations
– Requires additional library
– Unwieldy for simple use cases
Comparing Alternatives
• LINQ Expression Trees
– Introduced in .NET 3.5; initially somewhat limited
– Expanded in .NET 4.0; now roughly 1:1 with CIL
– Doesn’t support certain functional features like
closures
Comparing Alternatives
• Common Intermediate Language (CIL)
– Low-level; relatively difficult to work with
– Supports all CLR features
– F# Quotations don’t support all CLR features
●
Notably, throw and rethrow – these need to be
wrapped in a function and compiled using the proto
compiler
●
No fault/filter clauses
• F# Quotations don’t support open generics
Quotations: How-To
• Open some namespaces
• Define a module, then some functions within
the module
open System.Reflection
open Microsoft.FSharp.Reflection
open Microsoft.FSharp.Quotations
module Foo =
let addTwo x = x + 2
Quotations: How-To
• Apply [<ReflectedDefinition>] to your function
– Or, apply it to your module as a shortcut for applying it to
all functions in the module
module Foo =
/// Dummy class used to retrieve
/// the module type.
type internal Dummy = class end
[<ReflectedDefinition>]
let addTwo x = x + 2
Quotations: How-To
• Using Reflection, get the MethodInfo for your
function
• Call Expr.TryGetReflectedDefinition with the
MethodInfo to get the Expr for the method
Quotations: How-To
[<EntryPoint>]
let main argv =
let fooType = typeof<Foo.Dummy>.DeclaringType
let addTwoMethodInfo =
match fooType.GetMethod "addTwo" with
| null -> None
| x -> Some x
addTwoMethodInfo
|> Option.map Expr.TryGetReflectedDefinition
|> Option.iter (printfn "addTwo: %A")
Quotations: How-To
• For each active pattern in Quotations.Patterns,
there is a corresponding static member of the
Expr type.
– These are used to construct and destructure each
quotation “case”.
• Two types of quotations: typed and untyped
– Typed: Expr<‘T>
– Untyped: Expr
Quotations: How-To
• Expr<‘T> is just a wrapper around Expr
– Use the .Raw property for Expr<‘T> -> Expr
– Use the Coerce pattern for Expr -> Expr<‘T>
• Quoting an expression
– Typed: <@ fun x -> x + 2 @>
– Untyped: <@@ fun x -> x + 2 @@>
Quotations: How-To
• “Splicing” – a way to combine quotations
– Inserts one quotation into another
– Typed:
let bar = <@ 3 + "Blah".Length @>
let foo = <@ fun x -> x + %bar @>
– Untyped:
let bar = <@@ 3 + "Blah".Length @@>
let foo = <@@ fun x -> x + %%bar @@>
Quotations: How-To
• Note: You don’t always need
[<ReflectedDefinition>] to use quotations
• Using our previous example, this is equivalent
let addTwo = <@ fun x -> x + 2 @>
Computations on Trees
• When working with Quotations, it’s critical
you’re comfortable with trees and recursion
• Tree computations in imperative languages
usually built around the “visitor” pattern
– Visitor class usually holds private, mutable state
– Often implemented as an abstract base class per
tree type, and one virtual method per node type
– Mechanics of the traversal intermixed with
computation happening at nodes
Computations on Trees
• Possible to implement a functional alternative
to the “visitor” pattern?
• Knuth did – decades ago!
• Introducing “attribute grammars”
– Initially used as a means of describing how LL/LR
parsers annotate a parse tree
– Later, used to describe how “attributes” are
computed from on tree
Computations on Trees
• Attribute grammars are declarative
– They do not define any traversal order
• Attribute grammars allow you to define purely
functional, monadic computations over trees
– For those familiar with Haskell – attribute
evaluation is actually co-monadic
• AGs on ASTs (or Quotations) can be used to
implement purely functional AOP
Computations on Trees
• Three main kinds of attributes
• Inherited (L-attributes)
– Attribute “inherited” from parent node
– Compare to the reader workflow
• Synthesized (S-attributes)
– Attribute “synthesized” by a child node, passed
back up to parent node
– Compare to the writer workflow
Computations on Trees
• Threaded (SL-attributes)
– Attribute value inherited from parent node,
modified by child, then passed back up to parent
– Combination of Inherited and Synthesized
– Compare to the state workflow
• Attribute values can be int, string, UDTs, etc.
• They can also be tree nodes
– We can use this to define tree transformations
Exercises
• Implement a function(s) which, given an Expr:
– Print the equiv. F# source code
– Invert the mathematical operators (+)/(-), (*)/(/)
– Compute the set of methods called by the Expr
●
Bonus: Compute this transitively
– Determine if the Expr can ever raise an exn
– Determine if the Expr is pure (side-effect free)
– Rewrite it so all strings are passed through
String.Intern

Mais conteúdo relacionado

Mais procurados

C# 9 and 10 - What's cool?
C# 9 and 10 - What's cool?C# 9 and 10 - What's cool?
C# 9 and 10 - What's cool?Christian Nagel
 
History of F#, and the ML family of languages.
History of F#, and the ML family of languages. History of F#, and the ML family of languages.
History of F#, and the ML family of languages. Rachel Reese
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)lennartkats
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages mohamed drahem
 
Character sets and iconv
Character sets and iconvCharacter sets and iconv
Character sets and iconvDaniel_Rhodes
 
The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)lennartkats
 
C programming language
C programming languageC programming language
C programming languageMaha lakshmi
 
Procedure oriented programming
Procedure oriented programmingProcedure oriented programming
Procedure oriented programmingMrShahbazRafiq
 
Language Engineering in the Cloud
Language Engineering in the CloudLanguage Engineering in the Cloud
Language Engineering in the Cloudlennartkats
 
Async programming in f
Async programming in fAsync programming in f
Async programming in fBeauLiu
 
Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...SemWebPro
 
The GNOME way - What can we learn from and within the Open Documentation World
The GNOME way - What can we learn from and within the Open Documentation WorldThe GNOME way - What can we learn from and within the Open Documentation World
The GNOME way - What can we learn from and within the Open Documentation WorldRadina Matic
 

Mais procurados (20)

Introduction to F# 3.0
Introduction to F# 3.0Introduction to F# 3.0
Introduction to F# 3.0
 
C# 9 and 10 - What's cool?
C# 9 and 10 - What's cool?C# 9 and 10 - What's cool?
C# 9 and 10 - What's cool?
 
Swift vs. Language X
Swift vs. Language XSwift vs. Language X
Swift vs. Language X
 
History of F#, and the ML family of languages.
History of F#, and the ML family of languages. History of F#, and the ML family of languages.
History of F#, and the ML family of languages.
 
F# and the DLR
F# and the DLRF# and the DLR
F# and the DLR
 
Create Your Own Language
Create Your Own LanguageCreate Your Own Language
Create Your Own Language
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages
 
LIL Presentation
LIL PresentationLIL Presentation
LIL Presentation
 
Character sets and iconv
Character sets and iconvCharacter sets and iconv
Character sets and iconv
 
The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)
 
C programming language
C programming languageC programming language
C programming language
 
F# for Scala developers
F# for Scala developersF# for Scala developers
F# for Scala developers
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
Procedure oriented programming
Procedure oriented programmingProcedure oriented programming
Procedure oriented programming
 
Language Engineering in the Cloud
Language Engineering in the CloudLanguage Engineering in the Cloud
Language Engineering in the Cloud
 
Lexical1
Lexical1Lexical1
Lexical1
 
Async programming in f
Async programming in fAsync programming in f
Async programming in f
 
Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...
 
The GNOME way - What can we learn from and within the Open Documentation World
The GNOME way - What can we learn from and within the Open Documentation WorldThe GNOME way - What can we learn from and within the Open Documentation World
The GNOME way - What can we learn from and within the Open Documentation World
 

Semelhante a Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations code as-data for f#

Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#IndyMobileNetDev
 
Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#Dave Fancher
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigoujaxconf
 
F# for startups
F# for startupsF# for startups
F# for startupsjoelgrus
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...Jose Quesada (hiring)
 
Lisp, An Introduction.ppt
Lisp, An Introduction.pptLisp, An Introduction.ppt
Lisp, An Introduction.pptLuis Soza
 
F# for startups v2
F# for startups v2F# for startups v2
F# for startups v2joelgrus
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 
Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...InfinIT - Innovationsnetværket for it
 
The Final Frontier
The Final FrontierThe Final Frontier
The Final FrontierjClarity
 
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)Michael Rys
 

Semelhante a Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations code as-data for f# (20)

Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#
 
Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
 
F# for startups
F# for startupsF# for startups
F# for startups
 
10-DesignPatterns.ppt
10-DesignPatterns.ppt10-DesignPatterns.ppt
10-DesignPatterns.ppt
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
intro.ppt
intro.pptintro.ppt
intro.ppt
 
intro.ppt
intro.pptintro.ppt
intro.ppt
 
Lisp, An Introduction.ppt
Lisp, An Introduction.pptLisp, An Introduction.ppt
Lisp, An Introduction.ppt
 
F# for startups v2
F# for startups v2F# for startups v2
F# for startups v2
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...
 
Funtional Programming
Funtional ProgrammingFuntional Programming
Funtional Programming
 
The Final Frontier
The Final FrontierThe Final Frontier
The Final Frontier
 
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
 

Mais de Skills Matter

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard LawrenceSkills Matter
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmSkills Matter
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimSkills Matter
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlSkills Matter
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsSkills Matter
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Skills Matter
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Skills Matter
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldSkills Matter
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Skills Matter
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingSkills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveSkills Matter
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tSkills Matter
 
Bootstrapping a-devops-matter
Bootstrapping a-devops-matterBootstrapping a-devops-matter
Bootstrapping a-devops-matterSkills Matter
 

Mais de Skills Matter (20)

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberl
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.js
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source world
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testing
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
 
Serendipity-neo4j
Serendipity-neo4jSerendipity-neo4j
Serendipity-neo4j
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Plug 20110217
Plug   20110217Plug   20110217
Plug 20110217
 
Lug presentation
Lug presentationLug presentation
Lug presentation
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
 
Plug saiku
Plug   saikuPlug   saiku
Plug saiku
 
Huguk lily
Huguk lilyHuguk lily
Huguk lily
 
Bootstrapping a-devops-matter
Bootstrapping a-devops-matterBootstrapping a-devops-matter
Bootstrapping a-devops-matter
 

Último

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Último (20)

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations code as-data for f#

  • 1. F# Quotations: “Code as Data” Jack Pappas Dmitry Morozov SkillsMatter Progressive F# Tutorials NYC September 19th, 2013
  • 2. Code as Data • Code & Data – What is the difference? • Is there a difference? • Programs exist to process data – The F# compiler processes data (your source code) • Source code is no different than other kinds of data
  • 3. This Session • What is a “quoted expression”? – A simple, immutable data structure – Represents a fragment of F# code • Syllabus – Background – Working with Quotations – Manipulating Quotations – Applications of Quotations
  • 4. Background • The idea of treating code as data first appeared in Lisp Lisp F# Code (1 2 3) [1; 2; 3] Code as Data ‘(1 2 3) <@ [1; 2; 3] @>
  • 5. Background • A language that has the natural ability to manipulate itself is extremely powerful • “Amplify” a developer’s productivity using metaprogramming techniques
  • 6. Background • Other languages can manipulate their own code – clang: C++ program, manipulates C++ – Roslyn: C# library, manipulates C# – f2c: C program, manipulates FORTRAN and C • What makes Lisp and F# different? – Reflective meta-programming – Built-in language feature vs. external functionality
  • 7. Background • Now that we can manipulate code as data, what can we do with it? • Transform – modify, convert, translate • Analyze – Static analysis – Advanced testing techniques (e.g., verification) – Collect and record code metrics (e.g., complexity)
  • 8. Background • Execute – Interpret the code/data – Translate to another lang., compile, execute – Specialized hardware (e.g., GPU, FPGA) – Specialized execution (e.g., auto-parallelization) – Execute remotely (e.g., web service) – Some combination of the above – (Rarely) execute in same context, e.g., by translating to IL and executing
  • 9. Use Cases • LINQ support in F# – Extension of this idea: Cheney, Lindley, Wadler. “The essence of language-integrated query” • Use as an IL when developing type providers – Quotations much easier to work with – Create quotations, translate to IL
  • 10. Use Cases • Testing – Moq/Foq/Unquote • GPU programming – Compute: FSCL, QuantAlea – Graphics: SharpShaders (F# -> HLSL) • Web Development (F# -> JavaScript) – WebSharper – FunScript – PitFw
  • 11. Comparing Alternatives • What alternatives exist to quotations? – F# AST – LINQ Expression Trees – CIL (MSIL) • Imperative: Expression Trees, CIL – C# lambdas compiled into Expression Trees by the C# compiler • Functional: F# AST, Quotations
  • 12. Comparing Alternatives • F# AST – Designed for the compiler’s internal use – Carries more information than quotations – Requires additional library – Unwieldy for simple use cases
  • 13. Comparing Alternatives • LINQ Expression Trees – Introduced in .NET 3.5; initially somewhat limited – Expanded in .NET 4.0; now roughly 1:1 with CIL – Doesn’t support certain functional features like closures
  • 14. Comparing Alternatives • Common Intermediate Language (CIL) – Low-level; relatively difficult to work with – Supports all CLR features – F# Quotations don’t support all CLR features ● Notably, throw and rethrow – these need to be wrapped in a function and compiled using the proto compiler ● No fault/filter clauses • F# Quotations don’t support open generics
  • 15. Quotations: How-To • Open some namespaces • Define a module, then some functions within the module open System.Reflection open Microsoft.FSharp.Reflection open Microsoft.FSharp.Quotations module Foo = let addTwo x = x + 2
  • 16. Quotations: How-To • Apply [<ReflectedDefinition>] to your function – Or, apply it to your module as a shortcut for applying it to all functions in the module module Foo = /// Dummy class used to retrieve /// the module type. type internal Dummy = class end [<ReflectedDefinition>] let addTwo x = x + 2
  • 17. Quotations: How-To • Using Reflection, get the MethodInfo for your function • Call Expr.TryGetReflectedDefinition with the MethodInfo to get the Expr for the method
  • 18. Quotations: How-To [<EntryPoint>] let main argv = let fooType = typeof<Foo.Dummy>.DeclaringType let addTwoMethodInfo = match fooType.GetMethod "addTwo" with | null -> None | x -> Some x addTwoMethodInfo |> Option.map Expr.TryGetReflectedDefinition |> Option.iter (printfn "addTwo: %A")
  • 19. Quotations: How-To • For each active pattern in Quotations.Patterns, there is a corresponding static member of the Expr type. – These are used to construct and destructure each quotation “case”. • Two types of quotations: typed and untyped – Typed: Expr<‘T> – Untyped: Expr
  • 20. Quotations: How-To • Expr<‘T> is just a wrapper around Expr – Use the .Raw property for Expr<‘T> -> Expr – Use the Coerce pattern for Expr -> Expr<‘T> • Quoting an expression – Typed: <@ fun x -> x + 2 @> – Untyped: <@@ fun x -> x + 2 @@>
  • 21. Quotations: How-To • “Splicing” – a way to combine quotations – Inserts one quotation into another – Typed: let bar = <@ 3 + "Blah".Length @> let foo = <@ fun x -> x + %bar @> – Untyped: let bar = <@@ 3 + "Blah".Length @@> let foo = <@@ fun x -> x + %%bar @@>
  • 22. Quotations: How-To • Note: You don’t always need [<ReflectedDefinition>] to use quotations • Using our previous example, this is equivalent let addTwo = <@ fun x -> x + 2 @>
  • 23. Computations on Trees • When working with Quotations, it’s critical you’re comfortable with trees and recursion • Tree computations in imperative languages usually built around the “visitor” pattern – Visitor class usually holds private, mutable state – Often implemented as an abstract base class per tree type, and one virtual method per node type – Mechanics of the traversal intermixed with computation happening at nodes
  • 24. Computations on Trees • Possible to implement a functional alternative to the “visitor” pattern? • Knuth did – decades ago! • Introducing “attribute grammars” – Initially used as a means of describing how LL/LR parsers annotate a parse tree – Later, used to describe how “attributes” are computed from on tree
  • 25. Computations on Trees • Attribute grammars are declarative – They do not define any traversal order • Attribute grammars allow you to define purely functional, monadic computations over trees – For those familiar with Haskell – attribute evaluation is actually co-monadic • AGs on ASTs (or Quotations) can be used to implement purely functional AOP
  • 26. Computations on Trees • Three main kinds of attributes • Inherited (L-attributes) – Attribute “inherited” from parent node – Compare to the reader workflow • Synthesized (S-attributes) – Attribute “synthesized” by a child node, passed back up to parent node – Compare to the writer workflow
  • 27. Computations on Trees • Threaded (SL-attributes) – Attribute value inherited from parent node, modified by child, then passed back up to parent – Combination of Inherited and Synthesized – Compare to the state workflow • Attribute values can be int, string, UDTs, etc. • They can also be tree nodes – We can use this to define tree transformations
  • 28. Exercises • Implement a function(s) which, given an Expr: – Print the equiv. F# source code – Invert the mathematical operators (+)/(-), (*)/(/) – Compute the set of methods called by the Expr ● Bonus: Compute this transitively – Determine if the Expr can ever raise an exn – Determine if the Expr is pure (side-effect free) – Rewrite it so all strings are passed through String.Intern