SlideShare a Scribd company logo
Esoteric LINQ
AND STRUCTURAL MADNESS
I Think Therefore I Am

    Chris Eargle
    Mad Scientist
    Telerik Evangelist
    C# MVP
    INETA Board of Directors
    Contacts
         kodefuguru.com
         kodefuguru@live.com
         callto://kodefuguru
“   It is not enough to have a
    good mind; the main
    thing is to use it well.
      RENE DESCARTES
                                 ”
Prepare();
var mind = blown;
This presentation is brought to you by Telerik.
Don’t worry. This is hardcore ideas and code, not a sales pitch.
Agenda

    Background Information
        Data Structures
        Design Patterns
        LINQ
    LINQ to Functions
    LINQ to Graphs
    LINQ to Specifications
Data Structures
A PRIMER
Common Data Structures

    Primitive Types
    Composite Types
    Abstract Types
Primitive Types

    These are struct types in C#
    Represents a single value
    Examples: bool, char, float, int
Composite Types

    In C#, everything else is a form of a composite type
    Typical examples
        Array
        Record
             Tuple
             Struct (not the C# struct)
             Plain Old Data Structure
        Union
        Tagged Union – Union that tracks current type
        Object – Data + Behavior
Abstract Types

    These are abstract composite types, structural implementations vary
    Examples
        Dictionary
        List
        Set
        Tree
        Graph
Graph

    Composed of nodes (or vertices) and edges



               Node

                         1          2        Edge



                         3          4            5
Digraph

    Apply a direction
    Removing direction is called the “underlying graph.”




                           1          2

                           3          4           5
Weighted Graph

    Edge contains value
    Useful for determining optimal routes between destinations



                                2.2
                           1          2
                        3.7             6.0
                                1.5           0.5
                           3          4             5
Multigraph

    More than one edge allowed between nodes




                        1         2

                        3         4         5
Hypergraph

    Edges can connect more than two nodes
    I view hyper-edges as categories




                          1             2

                          3             4    5
Tree

    A graph with parent-child relationships
    No node can be the child of more than one node



                      1          2

                                 3             4      5

                                               6
List

      A graph where each node is connected to 1 or 2 nodes
      Explicitly has an order




                     1           2   3          4             5
Set Comparisons

    List – Ordered, allows duplicates, single type
    Tuple – Ordered, allows duplicates, multiple types
    Set – Unordered, no duplicates, single type
Design Patterns
A PRIMER
“   A general reusable
    solution to a commonly
    occurring problem.
      WIKIPEDIA
                                                                      ”
Even if you do not know design patterns, you’ve probably used them.
Types of Design Patterns

    Creational Patterns
    Structural Patterns
    Behavioral Patterns
    Concurrency Patterns
    Architectural Patterns
Structural Patterns

    Difference with Data Structures
        Focus is to use structure to enable behavior
        There is potential overlap with abstract types
    Examples
        Adapter
        Composite
        Decorator
        Façade
        Flyweight
Behavioral Patterns

    Difference with Structural
        Behavior isn’t necessarily driven by the structure
    Examples
        Chain of Responsibility
        Command
        Iterator
        Observer
        Specification
        Visitor
Iterator

    an object that provides a standard way to examine all element of
     any collection.


    Has a uniform interface for traversing many data structure without
     exposing their implementations.


    Supports concurrent iteration and element removal.


    No need to know the internal structure of collection.
Iterator

            Aggregate          Client        Iterator
           <<interface>>                  <<interface>>
       + CreateIterator()               + First()
                                        + Next()
                                        + IsDone()
                                        + CurrentItem



           ConcreteAggregate             ConcreteIterator


       + CreateIterator()
Observer

    An object, called the subject, maintains a list of its dependents


    Dependents are known as observers


    Observers are notified when subject’s state changes
Observer

                                                          Subject
                        Observer
                                                   +observers
                                                   +Register(observer)
                 +Notify()                         +Unregister(observer)
                                                   +Notify()




    ConcreteObserverA              ConcreteObserverB


   +Notify()
Visitor

     Separates an algorithm from the structure on which it operates
Visitor

               Elementlike       Client        Visitable
              <<interface>>                 <<interface>>
            +Accept(visitable)            +Visit(element)




                  Element                        Visitor


          +Accept(visitable)
Specification

    Separates business rules from business objects
    Represents object-oriented predicates and predicate combinators
    Predicate – conditionals that can be passed
    The pattern uses “IsSpecifiedBy” to indicate whether the predicate is
     successful
Specification

    ISpecification               CompositeSpecification
    <<Interface>>
 +And()                          +And()
 +IsSatisfiedBy()                +IsSatisfiedBy()
 +Not()                          +Not()
 +Or()                           +Or()




           AndSpecification            OrSpecification           NotSpecification

       +left : ISpecification      +left : ISpecification
       +right : ISpecification     +right : ISpecification   +wrapped : ISpecification
LINQ
A PRIMER
Language Integrated Query

    Interrogate / manipulate data
    Type safe
    Misunderstood
Example Query

 from x in object1
 from y in object2
 select x + y;       What can you tell me
                           about
                          object1?
LINQ to Objects

    This is LINQ over the iterator pattern
    The iterator pattern in C# is implemented with IEnumerable
    Much more declarative than foreach loops
    Lazy Execution
LINQ to SQL/EF/Etc

    Uses visitor pattern
    Lambdas represent Expressions rather than functions
    Visitor translates expressions into another language
Reactive

    LINQ to observer pattern
    Items are pushed instead of pulled
    Great for asynchronous programming
    Is now open source
Materialization

 sequence.ToList();


                      This is typically
                          wrong.
Materialization

 sequence.Materialize();




 public static IEnumberable<T> Materialize(
   this IEnumerable<T> sequence)
 {
     return sequence.ToArray();
 }
Memoization

    Best of both worlds: Lazy Execution and Materialized results
    Cache results as collection is iterated
Code
LINQ to Functions
FUNCTIONAL COMBINATORS
What Does LINQ to Functions Mean

    Applying LINQ to new forms require reimagining the DSL
    In the case of functions, LINQ combines functions
    Each LINQ method is a functional combinator
“   a combinator is a function
    which builds program
    fragments from program
    fragments…
     JOHN HUGHES
                                 ”
Code
LINQ to Graphs
VERTICES AND EDGES
Select



         1       2    v` + 1   2       3
                     Select
             3                     4
SelectMany



            1       2      v` + w`   2       3   3       4
1   2   ,               SelectMany
                3                        4           5
SelectMany



       Expand   2       3   3       4

                    4           5
SelectMany



               2       3
        Fold
                   4       5
Where



        1       2   v` % 2 == 1

                    Where         1   3
            3
Code
LINQ to Specifications
PREDICATE COMBINATORS
Explanation

    Predicates are functions, but they combine differently than other
     functions
    Therefore, it makes more sense to wrap them so specific
     combinators can be applied
LINQ Weirdness

 from x in specification
 where x != 0
 select !x;
Code
Q&A

More Related Content

PPTX
Class introduction in java
PPT
PPT
PDF
Object-oriented Basics
PPTX
Introduction to Client-Side Javascript
PDF
Clean code
PPT
object oriented programming language by c++
PPT
Java: Objects and Object References
Class introduction in java
Object-oriented Basics
Introduction to Client-Side Javascript
Clean code
object oriented programming language by c++
Java: Objects and Object References

What's hot (19)

PPT
Chapter 2 - Getting Started with Java
PPTX
Java Generics
PPT
PPSX
Oop features java presentationshow
PPS
Introduction to class in java
PPTX
Lecture 5
PDF
Sdtl manual
PPTX
Lecture 7 arrays
PPTX
03 object-classes-pbl-4-slots
PPT
Java căn bản - Chapter2
PPT
Object and Classes in Java
PPTX
Classes, objects in JAVA
PDF
ITFT-Classes and object in java
PPT
Java basic
PPTX
Design Patterns: Back to Basics
PDF
Lect 1-java object-classes
PDF
Built in classes in java
PPTX
Lecture 4_Java Method-constructor_imp_keywords
PPTX
Java fundamentals
Chapter 2 - Getting Started with Java
Java Generics
Oop features java presentationshow
Introduction to class in java
Lecture 5
Sdtl manual
Lecture 7 arrays
03 object-classes-pbl-4-slots
Java căn bản - Chapter2
Object and Classes in Java
Classes, objects in JAVA
ITFT-Classes and object in java
Java basic
Design Patterns: Back to Basics
Lect 1-java object-classes
Built in classes in java
Lecture 4_Java Method-constructor_imp_keywords
Java fundamentals
Ad

Similar to Esoteric LINQ and Structural Madness (20)

PPTX
OOP, API Design and MVP
PPTX
Solid OOPS
PDF
Neal Ford Emergent Design And Evolutionary Architecture
PDF
Clojure intro
PDF
Changes and Bugs: Mining and Predicting Development Activities
PPTX
Iterator - a powerful but underappreciated design pattern
PPTX
Evolution of Patterns
PDF
PPT
PDF
Objective-C
PPT
34. uml
PDF
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
PPTX
Graph Databases in the Microsoft Ecosystem
PPTX
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
PDF
The Ring programming language version 1.5.1 book - Part 5 of 180
PPT
PDF
Linked list basics
PDF
Hibernate 3
ODP
Clojure
OOP, API Design and MVP
Solid OOPS
Neal Ford Emergent Design And Evolutionary Architecture
Clojure intro
Changes and Bugs: Mining and Predicting Development Activities
Iterator - a powerful but underappreciated design pattern
Evolution of Patterns
Objective-C
34. uml
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Graph Databases in the Microsoft Ecosystem
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Sessisgytcfgggggggggggggggggggggggggggggggg
The Ring programming language version 1.5.1 book - Part 5 of 180
Linked list basics
Hibernate 3
Clojure
Ad

More from Chris Eargle (10)

PPTX
Bring your existing .net skills to a cms
PPTX
Hidden Gems of the Sitefinity API Webinar
PPTX
Amp Up Your Visual Studio Productivity
PPTX
Easier with visual studio productivity tools
PPTX
One Engine Two Tools
PPTX
2012 Q1 Tools for Better Code
PPTX
Deep Dive: MVC Controller Architecture
PPTX
Building a multi touch enabled windows 7 point of sale system
PPTX
Monadic Comprehensions and Functional Composition with Query Expressions
PDF
C# Ninjitsu
Bring your existing .net skills to a cms
Hidden Gems of the Sitefinity API Webinar
Amp Up Your Visual Studio Productivity
Easier with visual studio productivity tools
One Engine Two Tools
2012 Q1 Tools for Better Code
Deep Dive: MVC Controller Architecture
Building a multi touch enabled windows 7 point of sale system
Monadic Comprehensions and Functional Composition with Query Expressions
C# Ninjitsu

Esoteric LINQ and Structural Madness

  • 2. I Think Therefore I Am  Chris Eargle  Mad Scientist  Telerik Evangelist  C# MVP  INETA Board of Directors  Contacts  kodefuguru.com  kodefuguru@live.com  callto://kodefuguru
  • 3. It is not enough to have a good mind; the main thing is to use it well. RENE DESCARTES ” Prepare(); var mind = blown;
  • 4. This presentation is brought to you by Telerik. Don’t worry. This is hardcore ideas and code, not a sales pitch.
  • 5. Agenda  Background Information  Data Structures  Design Patterns  LINQ  LINQ to Functions  LINQ to Graphs  LINQ to Specifications
  • 7. Common Data Structures  Primitive Types  Composite Types  Abstract Types
  • 8. Primitive Types  These are struct types in C#  Represents a single value  Examples: bool, char, float, int
  • 9. Composite Types  In C#, everything else is a form of a composite type  Typical examples  Array  Record  Tuple  Struct (not the C# struct)  Plain Old Data Structure  Union  Tagged Union – Union that tracks current type  Object – Data + Behavior
  • 10. Abstract Types  These are abstract composite types, structural implementations vary  Examples  Dictionary  List  Set  Tree  Graph
  • 11. Graph  Composed of nodes (or vertices) and edges Node 1 2 Edge 3 4 5
  • 12. Digraph  Apply a direction  Removing direction is called the “underlying graph.” 1 2 3 4 5
  • 13. Weighted Graph  Edge contains value  Useful for determining optimal routes between destinations 2.2 1 2 3.7 6.0 1.5 0.5 3 4 5
  • 14. Multigraph  More than one edge allowed between nodes 1 2 3 4 5
  • 15. Hypergraph  Edges can connect more than two nodes  I view hyper-edges as categories 1 2 3 4 5
  • 16. Tree  A graph with parent-child relationships  No node can be the child of more than one node 1 2 3 4 5 6
  • 17. List  A graph where each node is connected to 1 or 2 nodes  Explicitly has an order 1 2 3 4 5
  • 18. Set Comparisons  List – Ordered, allows duplicates, single type  Tuple – Ordered, allows duplicates, multiple types  Set – Unordered, no duplicates, single type
  • 20. A general reusable solution to a commonly occurring problem. WIKIPEDIA ” Even if you do not know design patterns, you’ve probably used them.
  • 21. Types of Design Patterns  Creational Patterns  Structural Patterns  Behavioral Patterns  Concurrency Patterns  Architectural Patterns
  • 22. Structural Patterns  Difference with Data Structures  Focus is to use structure to enable behavior  There is potential overlap with abstract types  Examples  Adapter  Composite  Decorator  Façade  Flyweight
  • 23. Behavioral Patterns  Difference with Structural  Behavior isn’t necessarily driven by the structure  Examples  Chain of Responsibility  Command  Iterator  Observer  Specification  Visitor
  • 24. Iterator  an object that provides a standard way to examine all element of any collection.  Has a uniform interface for traversing many data structure without exposing their implementations.  Supports concurrent iteration and element removal.  No need to know the internal structure of collection.
  • 25. Iterator Aggregate Client Iterator <<interface>> <<interface>> + CreateIterator() + First() + Next() + IsDone() + CurrentItem ConcreteAggregate ConcreteIterator + CreateIterator()
  • 26. Observer  An object, called the subject, maintains a list of its dependents  Dependents are known as observers  Observers are notified when subject’s state changes
  • 27. Observer Subject Observer +observers +Register(observer) +Notify() +Unregister(observer) +Notify() ConcreteObserverA ConcreteObserverB +Notify()
  • 28. Visitor  Separates an algorithm from the structure on which it operates
  • 29. Visitor Elementlike Client Visitable <<interface>> <<interface>> +Accept(visitable) +Visit(element) Element Visitor +Accept(visitable)
  • 30. Specification  Separates business rules from business objects  Represents object-oriented predicates and predicate combinators  Predicate – conditionals that can be passed  The pattern uses “IsSpecifiedBy” to indicate whether the predicate is successful
  • 31. Specification ISpecification CompositeSpecification <<Interface>> +And() +And() +IsSatisfiedBy() +IsSatisfiedBy() +Not() +Not() +Or() +Or() AndSpecification OrSpecification NotSpecification +left : ISpecification +left : ISpecification +right : ISpecification +right : ISpecification +wrapped : ISpecification
  • 33. Language Integrated Query  Interrogate / manipulate data  Type safe  Misunderstood
  • 34. Example Query from x in object1 from y in object2 select x + y; What can you tell me about object1?
  • 35. LINQ to Objects  This is LINQ over the iterator pattern  The iterator pattern in C# is implemented with IEnumerable  Much more declarative than foreach loops  Lazy Execution
  • 36. LINQ to SQL/EF/Etc  Uses visitor pattern  Lambdas represent Expressions rather than functions  Visitor translates expressions into another language
  • 37. Reactive  LINQ to observer pattern  Items are pushed instead of pulled  Great for asynchronous programming  Is now open source
  • 38. Materialization sequence.ToList(); This is typically wrong.
  • 39. Materialization sequence.Materialize(); public static IEnumberable<T> Materialize( this IEnumerable<T> sequence) { return sequence.ToArray(); }
  • 40. Memoization  Best of both worlds: Lazy Execution and Materialized results  Cache results as collection is iterated
  • 41. Code
  • 43. What Does LINQ to Functions Mean  Applying LINQ to new forms require reimagining the DSL  In the case of functions, LINQ combines functions  Each LINQ method is a functional combinator
  • 44. a combinator is a function which builds program fragments from program fragments… JOHN HUGHES ”
  • 45. Code
  • 47. Select 1 2 v` + 1 2 3 Select 3 4
  • 48. SelectMany 1 2 v` + w` 2 3 3 4 1 2 , SelectMany 3 4 5
  • 49. SelectMany Expand 2 3 3 4 4 5
  • 50. SelectMany 2 3 Fold 4 5
  • 51. Where 1 2 v` % 2 == 1 Where 1 3 3
  • 52. Code
  • 54. Explanation  Predicates are functions, but they combine differently than other functions  Therefore, it makes more sense to wrap them so specific combinators can be applied
  • 55. LINQ Weirdness from x in specification where x != 0 select !x;
  • 56. Code
  • 57. Q&A