Putting it all together: LINQ as an Example

Similar documents
Concepts behind the C# 3 language. Faculty of Mathematics and Physics, Charles University in Prague

Previous C# Releases. C# 3.0 Language Features. C# 3.0 Features. C# 3.0 Orcas. Local Variables. Language Integrated Query 3/23/2007

C # Version 3.0 Specification

Functional programming in C#

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Final-Term Papers Solved MCQS with Reference

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

JavaScript: Sort of a Big Deal,

Control in Sequential Languages

LinQ Why we have to teach functional programmming

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

JavaScript: Coercion, Functions, Arrays

Introduction to LINQ. Paul Litwin Collaborative Data Services (CDS)

Why do you want to know about functional programming?

INF3110 Programming Languages Runtime Organization part II

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

CSCI-GA Scripting Languages

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

CS152 Programming Language Paradigms Prof. Tom Austin, Fall Syntax & Semantics, and Language Design Criteria

Functional Programming and Haskell

CS 342 Lecture 6 Scheme Procedures and Closures By: Hridesh Rajan

Pierce Ch. 3, 8, 11, 15. Type Systems

CSE 431S Type Checking. Washington University Spring 2013

Chapter 11 :: Functional Languages

Semantic Analysis. Lecture 9. February 7, 2018

Asynchronous Functions in C#

Advances in Programming Languages

The role of semantic analysis in a compiler

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

Lecture 4 Memory Management

CS 11 Haskell track: lecture 1

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Structured bindings with polymorphic lambas

The SPL Programming Language Reference Manual

Recap: Functions as first-class values

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

G Programming Languages - Fall 2012

Introduction to Functional Programming

LECTURE 16. Functional Programming

Anonymous Functions CMSC 330: Organization of Programming Languages

Advanced Programming C# Lecture 10. dr inż. Małgorzata Janik

Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam

An introduction to C++ template programming

Type Inference. Prof. Clarkson Fall Today s music: Cool, Calm, and Collected by The Rolling Stones

C++11 and Compiler Update

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

A Programming Languages Course at Web Speed

Programming Languages

Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CS101 Introduction to Programming Languages and Compilers

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

Show and Tell. 1. Plan 9 Things (brief) 2. An Extensible Compiler for Systems Programming. Russ Cox 1127 Show and Tell April 19, 2005

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?

Introduce C# as Object Oriented programming language. Explain, tokens,

C# in Depth SECOND EDITION JON SKEET. MANNING Greenwich (74 w. long.)

INF3110 Programming Languages Runtime Organization part II

An Introduction to Scheme

The Substitution Model

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Compiler Construction I

CS558 Programming Languages

Pass by Value. Pass by Value. Our programs are littered with function calls like f (x, 5).

IMPLEMENTING THE LINQ QUERY LANGUAGE INTO THE C++ PROGRAMMING LANGUAGE USING A PREPROCESSOR

Motivation for typed languages

CS313D: ADVANCED PROGRAMMING LANGUAGE

use attributes (); # optional, to get subroutine declarations = attributes::get(\&foo);

7. Relational Calculus (Part I) 7.1 Introduction

Weeks 6&7: Procedures and Parameter Passing

Type Bindings. Static Type Binding

Concepts of Programming Languages

Midterm CSE 131B Spring 2005

LINQ Language-Integrated Query Introduction

FUNCTIONAL AND LOGIC PROGRAMS

Functional Programming

CS 314 Principles of Programming Languages

Upcoming Features in C# Mads Torgersen, MSFT

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Expressions and Assignment

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Programming Languages Third Edition. Chapter 7 Basic Semantics

Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Organization of Programming Languages CS3200/5200N. Lecture 11

Scope, Functions, and Storage Management

Basic Scheme February 8, Compound expressions Rules of evaluation Creating procedures by capturing common patterns

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Scheme: Strings Scheme: I/O

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

MIT Semantic Analysis. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology

Object-Oriented Programming in C# (VS 2015)

The PCAT Programming Language Reference Manual

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Chapter 4 Defining Classes I

Transcription:

Putting it all together: LINQ as an Example The Problem: SQL in Code Programs often connect to database servers. Database servers only speak SQL. Programs have to construct SQL strings. PHP example: if (some_condition()) { $q = mysql_query( select name from user were id = $id )... When will the problem be detected? 2

Searching in Collections Begin with a simple array of, say, Customers. Customer[] customers = new Customer[30]; customers[0] = new Customer( ); customers[29] = new Customer( ); 3 Searching in Collections: The Old Way Find the names of all London customers: List<string> londoners = new List<string>(); foreach (Customer c in customers) { if (c.city == London ) { londoners.add(c.name); 4

Searching in Collections: The LINQ Way Returns a simple array! string[] londoners = from c in customers where c.city == London select c.name; No loops! Declarative! SQL-like! 5 Searching in Collections: The LINQ Way LINQ is a C # feature Introduced in C # 3.0. LINQ = Language INtegrated Query So far, this is just list comprehension added to C #. What did it take to add list comprehension to the language?

LINQ: How Does It Work? LINQ syntax = shorthand for method invocation. Syntactic sugar, using Translation maps 7 Syntax Translation Example string[] londoners = from c in customers where c.city == London select c.name; string[] londoners = customers. Where(expression). Select(expression); 8

Expressions == Methods? Where() wants a Boolean method. The method acts as a filter. Likewise for Select(): a translation method. 9 Translating Expressions Problem: Translating c.city == London to a boolean expression e, such that Where(e) is valid? 10

C # Delegates C # delegates: method pointers. Since C # 1.0. class Demo { delegate void Foo(); void Bar() { do something ; void Test() { Foo mydelegate = new Foo(Bar); // pointer to Bar() mydelegate(); // invoke 11 Delegates as Arguments Delegates can be passed as arguments. Event handlers, jobs for threads, etc. class Demo { void Job() { the job to carry out ; void Test() { Thread worker = new Thread( new ThreadStart(Job)); worker.start(); 12

Anonymous Methods Nameless methods = on-the-fly delegates: class Demo { delegate void Foo(); void Test() { Foo mydelegate = delegate() { do something ; mydelegate(); // invoke 13 Syntax Translation Example string[] londoners = from c in customers where c.city == London select c.name; string[] londoners = customers. Where(delegate(Customer c) { return c.city == London ; ). Select(delegate(Customer c) { return c.name ); 14

Well, Not Really. Where(), etc. accept delegate methods. But LINQ creates lambda expressions. Seamless conversion via coercion. 15 Syntax Translation Example string[] londoners = from c in customers where c.city == London select c.name; string[] londoners = customers. Where(c => c.city == London ). Select(c => c.name); 16

Lambda Expressions Lambda expression syntax: Shades of ML (argumentlist) => expression oneargument => expression Arguments optionally typed. Type inference mechanism. More on that later 17 Where s Where()? We invoked Where() on Customers[]. On the resulting Customers[], we invoked Select(). New methods for arrays!? 18

Extension Methods class Utils { public static char firstchar(this string s) { return s.charat(0); So far, just a simple static method. Can be used like any other. 19 Extension Methods But now Using Utils; class Demo { void Foo() { string s = Hello ; Console.WriteLine(s.firstChar()); 20

Extension Methods Static methods that seem to extend existing types. Where(), Select(), etc. extend array types in this manner. 21 Query Your Own Types! LINQ can be applied to any type, not just built-in arrays and lists. Just implement Where(), Select(), etc. 22

LINQ and Relational Data Let s obtain a DB-table type, and query it. DbCustomers customers = new DbCustomers( my.mdb ); string[] londoners = from c in customers where c.city == London select c.name; 23 This Makes No Sense! But Where() applies the filter to every record. on the client! SELECT * FROM CUSTOMERS, and filter with a simple loop!? 24

Back To Lambda Expressions Lambda expressions can be converted to anonymous methods. Can also be coerced to expression trees. A run-time representation of the syntax tree. 25 Example Our code yields: string[] londoners = customers. Where(c => c.city == London ). Select(c => c.name); where customers is of type DbCustomers. No DbCustomers.Where(delegate(Customer c)) method exists. However: DbCustomers.Where( Expression<Func<Customer,bool>> xt) 26

What Are Expression Trees? Any valid expression is converted by the compiler to an expression tree. a.k.a. the abstract syntax tree of the expression. Normal part of the compilation process, in any language! Examples: 5 + 3 * 2 c.city == London + == 5 *. (dot) London 3 2 c city 27 Expression Trees Normally, expression trees only exist at compile-time. In C #, the compiler can create a run-time representation of the expression tree. The language has a data type for expression trees. Represents lambda expressions at runtime. Used for generating SQL at runtime. Guaranteed to be syntactically valid, since it was created from a valid C # expression. 28

It s Just Coercion So, LINQ converts into expressions that use Where(...), Select(...), etc. For some classes, Where(...) and Select(...) accept delegates; for other classes, they accept expression trees. Lambda expressions can be coerced into either. 29 Projections Using LINQ s select: from c in customers where c.city == London select new AddressBookEntry(c.Name, c.phone); 30

Pre-Defined Types Only? But The projection type (e.g., AddressBookEntry) must be predefined! 31 Ad-Hoc Types new { [name 1 =] expr 1,, [ name n =] expr n Type implied by types of exprs. Example: If name is not specified, and expr is either property or x.property, then property s name will be used. from c in customers where c.city == London select new { c.name, c.phone ; 32

Ad-Hoc Types are Nameless How do we store the result???? q = from select new { ; The ad-hoc type is nameless! 33 Auto-Typed Variables var x = 7; // x will be of type int var q = from select new { ; // q will be an array of the anonymous type Console.WriteLine(q[0].Name); Local variables only. No auto-typing for fields or formal parameters. 34

Summary LINQ adds static SQL expression correctness to C #. To do this, the following features were added to C # : Lambda expressions. Extension methods. Expression types. List comprehension. Anonymous data types. Type inference. 35 There s More There are several LINQ features we did not present here, such as: Grouping ( GROUP BY in SQL) Joins (selecting from multiple tables)... These require even more language features, such as closures. 36

What Is Happening to Languages? As new features are added to programming languages, the languages evolve. Many of the features come from research or experimental languages. Note how many of the new C # features discussed here come from functional languages like ML, Haskell or LISP: Lambda expressions, expression types, list comprehension, anonymous data types, type inference... 37 Confessions of a Used Programming Language Salesman An 2007 essay by Eric Meijer (Microsoft). Discusses how features from functional languages slowly creep into mainstream languages. Functional programming has finally reached the masses, except that it is called Visual Basic 9 instead of Haskell 98. 38

A Glimpse Into the Future: LISP (1958) We have seen the power of representing program source at runtime (expression trees). In LISP, program source can be represented at runtime, but also generated at runtime (or compile-time). Source code itself is a data structure (a list). LISP macros are light-years ahead of C/C++ macros. 39 A Glimpse Into the Future: LISP (1958) 50 years later, LISP features are slowly re-appearing in mainstream languages. e.g., garbage collection, aspect-oriented programming, and more. Conclusions: a. Learn from history. b. Know LISP, Haskell, etc: once you really understand them, it will give you serious advantages over ignorant software engineers (even if you never use these languages in practice). 40