SlideShare una empresa de Scribd logo
1 de 22
Queries in general-purpose
  programming languages
Languages
Theory
  Relational algebra
  Monads and comprehensions

Haskell and Links
  Monad comprehensions
  Comprehensions with group and order

C# and F#
  Language integrated query (LINQ)
  Extensible query syntax in F# 3.0
Problems
Expressing queries
  What operations can we use?
  What is the right syntax for queries?
  Should the syntax be extensible?

Compiling queries
  How to turn normal code to SQL?
  How to turn normal code to efficient SQL?
  Dealing with functions in SQL code
Theory
Monads and monad
comprehensions in Haskell
Monad comprehensions

[ p.Name | p <- db.Products, p.Price > 10 ]




 db.Products `bind` (p ->
   if (p.Price > 10) then return p.Name
   else zero)
Monadic bind and joins
Join using comprehensions
  [ (p.Name, c.CategoryName)
       | p <- db.Products, c <- db.Categories
       , p.CategoryID = c.ID ]

Translation using monads
   db.Products `bind` (p ->
     db.Categories `bind` (c ->
       if (p.CategoryID = c.ID) then
         return (p.Name, c.CategoryName)
       else zero))

  Multiple uses of bind are nested
  Second data source may depend on values from first!
Comparing bind and join
Standard join
  Two independent data sources
  Equality condition on some projected values
    [ (p, c) | p <- db.Products, c <- db.Categories
             , p.CategoryID = c.ID ]

But bind allows more
  Second data source may depend on first
  Can use arbitrary conditions
    [ (p1.Name, p2.Name)
       | p1 <- Products
       , p2 <- [ p | p <- Products, p.Price > p1.Price ] ]
Adding ordering and grouping
Adding ordering and grouping

[ p | p <- db.Products, then reverse ]
[ p | p <- db.Products, then order by p.Price ]




[ p | …, then group by p.CategoryID ]
[ p | …, then group by p.CategoryID using groupAdj ]
SQL-style relational
queries in LINQ using C#
LINQ Overview
Query example
  from p in db.Products
  join c in db.Categories on p.CategoryID equals c.ID
  select new { p.Name, c.CategoryName }

Translating to SQL
  All operations have a corresponding method
   db.Products.Where(p => p.Price > 10)
   db.Products.Select(p => p.Name)

  Lambda function translated as expression tree
  Expression trees composed and processed
Expressing queries
Selection and projection
  from p in db.Products where p.Price > 10 select p
  from p in db.Products select p.Name

Ordering
  from p in db.Products orderby p.Price select p

Grouping
  from p in db.Products group p by p.CategoryID

Joins (products with selection)
  from p in db.Products
  join c in db.Categories on p.CategoryID equals c.ID
  select new { ... }
Customizing LINQ operators
Operations depend on the data source
  Syntax is translated to method calls
    from p in db.Products group p by p.CategoryID
    db.Products.GroupBy(p => p.CategoryID)
  Wrap collection and then use different operator
    from p in db.Products.WithAdjacentGrouping()
    group p by p.CategoryID

    WithAdjacentGrouping : IE<T> -> IEWithGroup<T>
    GroupBy : IEWithGroup<T> -> IEWithGroup<IEWithGroup<T>>


Various applications
  LINQ over events, Parallel implementation
Writing joins in LINQ
Syntax for joins
  Independent sources; equality condition only
    from p in db.Products
    join c in db.Categories on p.CategoryID equals c.ID
    select …

Using multiple from clauses
  Later from can depend on previous variables
  We can write arbitrary conditions
    from p in db.Products
    from c in db.Categories.Where(c => p.CategoryID == c.ID)
    where c.Name != "Stuff"
Joins and theory
Multiple from clauses
  Uses an operation similar to Bind
   SelectMany : M<S> -> (S -> M<C>) -> (S * C -> R) -> M<R>

  Can be implemented using Bind
   Bind      : M<S> -> (S -> M<R>) -> M<R>
   StrengthL : V * M<S> -> M<V * S>


Syntax for joins
  Can be defined using SelectMany, but not vice versa
    Join : M<A> -> M<B> -> (A -> K) -> (B -> K)
                -> (A * B -> R) -> M<R>

  Resembles operation of “applicative functors”
More flexible
queries in F# 3.0
Queries in F# 3.0
Design between Haskell and C#
  Can define custom operations
    query { for p in db.Products do
            orderBy p.Price
            takeWhile (p.Price > 100) }

  Here orderBy and takeWhile are not built-in

Two kinds of custom operations
  Preserve variable scope (orderBy, where, …)
  Require re-binding (groupBy)
What can be done in F# 3.0?
Better queries for OData
  Open standard for REST based queries
  Supports only subset of query operations

Expanding dependent tables explicitly
   query { for title in db.Movies do
           select title.Awards }

  Wrong! We did not say we will use Awards
   query { for title in db.Movies do
           expand title.Awards
           select title.Awards }


Other interesting areas: NoSQL, etc.
Some questions about queries
    that I’m interested in…
Possible questions
Advanced type checking
  Translating custom functions to SQL
  Limiting operations and allowed patterns (OData)

Expressivity
    What are other join-like operations?
    Aren’t monads and bind too powerful?
    Are we missing other important operations?
    What else is there than just lists…

Classical problems
  Optimizing queries, efficient compilation
References
Haskell and comprehensions
  Comprehensive Comprehensions:
   comprehensions with "Order by" and "Group by"
  Bringing Back Monad Comprehensions
  Monad Comprehensions:
   A Versatile Representation for Queries

LINQ, C# and F#
  C# Language Specification
  msdn.microsoft.com/en-us/library/bb397676.aspx
  tomasp.net/blog/idioms-in-linq.aspx

Más contenido relacionado

La actualidad más candente

Basic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder KalerBasic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder Kaler
Avjinder (Avi) Kaler
 

La actualidad más candente (19)

Grouping & Summarizing Data in R
Grouping & Summarizing Data in RGrouping & Summarizing Data in R
Grouping & Summarizing Data in R
 
Get up to Speed (Quick Guide to data.table in R and Pentaho PDI)
Get up to Speed (Quick Guide to data.table in R and Pentaho PDI)Get up to Speed (Quick Guide to data.table in R and Pentaho PDI)
Get up to Speed (Quick Guide to data.table in R and Pentaho PDI)
 
Pig statements
Pig statementsPig statements
Pig statements
 
Introduction to pandas
Introduction to pandasIntroduction to pandas
Introduction to pandas
 
Basic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder KalerBasic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder Kaler
 
Data Analysis in Python
Data Analysis in PythonData Analysis in Python
Data Analysis in Python
 
Text Mining with R
Text Mining with RText Mining with R
Text Mining with R
 
Coding T-SQL in a Team Environment
Coding T-SQL in a Team EnvironmentCoding T-SQL in a Team Environment
Coding T-SQL in a Team Environment
 
Working with Complex Types in DataFrames: Optics to the Rescue
Working with Complex Types in DataFrames: Optics to the RescueWorking with Complex Types in DataFrames: Optics to the Rescue
Working with Complex Types in DataFrames: Optics to the Rescue
 
Manipulating Data using DPLYR in R Studio
Manipulating Data using DPLYR in R StudioManipulating Data using DPLYR in R Studio
Manipulating Data using DPLYR in R Studio
 
Genomic Selection with Bayesian Generalized Linear Regression model using R
Genomic Selection with Bayesian Generalized Linear Regression model using RGenomic Selection with Bayesian Generalized Linear Regression model using R
Genomic Selection with Bayesian Generalized Linear Regression model using R
 
Reading Data into R
Reading Data into RReading Data into R
Reading Data into R
 
Introduction to R Programming
Introduction to R ProgrammingIntroduction to R Programming
Introduction to R Programming
 
R + 15 minutes = Hadoop cluster
R + 15 minutes = Hadoop clusterR + 15 minutes = Hadoop cluster
R + 15 minutes = Hadoop cluster
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
Introduction to MongoDB at IGDTUW
Introduction to MongoDB at IGDTUWIntroduction to MongoDB at IGDTUW
Introduction to MongoDB at IGDTUW
 
Introduction to TDD (PHPunit examples)
Introduction to TDD (PHPunit examples)Introduction to TDD (PHPunit examples)
Introduction to TDD (PHPunit examples)
 
Introduction to Data Mining with R and Data Import/Export in R
Introduction to Data Mining with R and Data Import/Export in RIntroduction to Data Mining with R and Data Import/Export in R
Introduction to Data Mining with R and Data Import/Export in R
 

Destacado

Destacado (8)

Tics
TicsTics
Tics
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#
 
F# Tutorial @ QCon
F# Tutorial @ QConF# Tutorial @ QCon
F# Tutorial @ QCon
 
Presentation Earth Saver Canvas Bags
Presentation Earth Saver Canvas BagsPresentation Earth Saver Canvas Bags
Presentation Earth Saver Canvas Bags
 
F# on the Server-Side
F# on the Server-SideF# on the Server-Side
F# on the Server-Side
 
Academia
AcademiaAcademia
Academia
 
Social Media in Small Business is Anything But Small
Social Media in Small Business is Anything But SmallSocial Media in Small Business is Anything But Small
Social Media in Small Business is Anything But Small
 

Similar a Queries in general purpose languages

Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
Srinivasa GV
 

Similar a Queries in general purpose languages (20)

Document databases
Document databasesDocument databases
Document databases
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
SF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDBSF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDB
 
GraphQL in Symfony
GraphQL in SymfonyGraphQL in Symfony
GraphQL in Symfony
 
MongoDB Aggregation MongoSF May 2011
MongoDB Aggregation MongoSF May 2011MongoDB Aggregation MongoSF May 2011
MongoDB Aggregation MongoSF May 2011
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and Workshop
 
Adventures in TclOO
Adventures in TclOOAdventures in TclOO
Adventures in TclOO
 
AIA101.2.Access Queries Accelerated
AIA101.2.Access Queries AcceleratedAIA101.2.Access Queries Accelerated
AIA101.2.Access Queries Accelerated
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
Building DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language WorkbenchBuilding DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language Workbench
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDB
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
 
Functions and Arguments in Python
Functions and Arguments in PythonFunctions and Arguments in Python
Functions and Arguments in Python
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...
 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 

Más de Tomas Petricek

Más de Tomas Petricek (14)

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
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional Way
 
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)
 
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
 
Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#
 
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
 
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)
 
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#
 
Teaching F#
Teaching F#Teaching F#
Teaching F#
 
F# in MonoDevelop
F# in MonoDevelopF# in MonoDevelop
F# in MonoDevelop
 
Concurrent programming with Agents
Concurrent programming with AgentsConcurrent programming with Agents
Concurrent programming with Agents
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Queries in general purpose languages

  • 1. Queries in general-purpose programming languages
  • 2. Languages Theory  Relational algebra  Monads and comprehensions Haskell and Links  Monad comprehensions  Comprehensions with group and order C# and F#  Language integrated query (LINQ)  Extensible query syntax in F# 3.0
  • 3. Problems Expressing queries  What operations can we use?  What is the right syntax for queries?  Should the syntax be extensible? Compiling queries  How to turn normal code to SQL?  How to turn normal code to efficient SQL?  Dealing with functions in SQL code
  • 6. Monad comprehensions [ p.Name | p <- db.Products, p.Price > 10 ] db.Products `bind` (p -> if (p.Price > 10) then return p.Name else zero)
  • 7. Monadic bind and joins Join using comprehensions [ (p.Name, c.CategoryName) | p <- db.Products, c <- db.Categories , p.CategoryID = c.ID ] Translation using monads db.Products `bind` (p -> db.Categories `bind` (c -> if (p.CategoryID = c.ID) then return (p.Name, c.CategoryName) else zero))  Multiple uses of bind are nested  Second data source may depend on values from first!
  • 8. Comparing bind and join Standard join  Two independent data sources  Equality condition on some projected values [ (p, c) | p <- db.Products, c <- db.Categories , p.CategoryID = c.ID ] But bind allows more  Second data source may depend on first  Can use arbitrary conditions [ (p1.Name, p2.Name) | p1 <- Products , p2 <- [ p | p <- Products, p.Price > p1.Price ] ]
  • 10. Adding ordering and grouping [ p | p <- db.Products, then reverse ] [ p | p <- db.Products, then order by p.Price ] [ p | …, then group by p.CategoryID ] [ p | …, then group by p.CategoryID using groupAdj ]
  • 12. LINQ Overview Query example from p in db.Products join c in db.Categories on p.CategoryID equals c.ID select new { p.Name, c.CategoryName } Translating to SQL  All operations have a corresponding method db.Products.Where(p => p.Price > 10) db.Products.Select(p => p.Name)  Lambda function translated as expression tree  Expression trees composed and processed
  • 13. Expressing queries Selection and projection from p in db.Products where p.Price > 10 select p from p in db.Products select p.Name Ordering from p in db.Products orderby p.Price select p Grouping from p in db.Products group p by p.CategoryID Joins (products with selection) from p in db.Products join c in db.Categories on p.CategoryID equals c.ID select new { ... }
  • 14. Customizing LINQ operators Operations depend on the data source  Syntax is translated to method calls from p in db.Products group p by p.CategoryID db.Products.GroupBy(p => p.CategoryID)  Wrap collection and then use different operator from p in db.Products.WithAdjacentGrouping() group p by p.CategoryID WithAdjacentGrouping : IE<T> -> IEWithGroup<T> GroupBy : IEWithGroup<T> -> IEWithGroup<IEWithGroup<T>> Various applications  LINQ over events, Parallel implementation
  • 15. Writing joins in LINQ Syntax for joins  Independent sources; equality condition only from p in db.Products join c in db.Categories on p.CategoryID equals c.ID select … Using multiple from clauses  Later from can depend on previous variables  We can write arbitrary conditions from p in db.Products from c in db.Categories.Where(c => p.CategoryID == c.ID) where c.Name != "Stuff"
  • 16. Joins and theory Multiple from clauses  Uses an operation similar to Bind SelectMany : M<S> -> (S -> M<C>) -> (S * C -> R) -> M<R>  Can be implemented using Bind Bind : M<S> -> (S -> M<R>) -> M<R> StrengthL : V * M<S> -> M<V * S> Syntax for joins  Can be defined using SelectMany, but not vice versa Join : M<A> -> M<B> -> (A -> K) -> (B -> K) -> (A * B -> R) -> M<R>  Resembles operation of “applicative functors”
  • 18. Queries in F# 3.0 Design between Haskell and C#  Can define custom operations query { for p in db.Products do orderBy p.Price takeWhile (p.Price > 100) }  Here orderBy and takeWhile are not built-in Two kinds of custom operations  Preserve variable scope (orderBy, where, …)  Require re-binding (groupBy)
  • 19. What can be done in F# 3.0? Better queries for OData  Open standard for REST based queries  Supports only subset of query operations Expanding dependent tables explicitly query { for title in db.Movies do select title.Awards }  Wrong! We did not say we will use Awards query { for title in db.Movies do expand title.Awards select title.Awards } Other interesting areas: NoSQL, etc.
  • 20. Some questions about queries that I’m interested in…
  • 21. Possible questions Advanced type checking  Translating custom functions to SQL  Limiting operations and allowed patterns (OData) Expressivity  What are other join-like operations?  Aren’t monads and bind too powerful?  Are we missing other important operations?  What else is there than just lists… Classical problems  Optimizing queries, efficient compilation
  • 22. References Haskell and comprehensions  Comprehensive Comprehensions: comprehensions with "Order by" and "Group by"  Bringing Back Monad Comprehensions  Monad Comprehensions: A Versatile Representation for Queries LINQ, C# and F#  C# Language Specification  msdn.microsoft.com/en-us/library/bb397676.aspx  tomasp.net/blog/idioms-in-linq.aspx