SlideShare a Scribd company logo
1 of 20
C# is a functionalC# is a functional
programming languageprogramming language
Andrew Kennedy
Microsoft Research Cambridge
Quicksort revisitedQuicksort revisited
Func<intlist, intlist> Sort =
xs =>
xs.Case(
() => xs,
(head,tail) => (Sort(tail.Where(x => x < head)))
.Concat
(Single(head))
.Concat
(Sort(tail.Where(x => x >= head)))
);
Name the language... C# 3.0
type inference
append
higher-order function
parameterized type of functions
recursion
filter
lambda expression
The gap narrows...The gap narrows...
 C# 3.0 has many features well-known to functional programmers
◦ Parameterized types and polymorphic functions (generics)
◦ First-class functions (delegates)
◦ Lightweight lambda expressions & closure conversion
◦ Type inference (for locals and lambdas)
◦ Streams (iterators)
◦ A library of higher-order functions for collections & iterators
◦ And even: GADTs (polymorphic inheritance)
 This talk: is it serious competition for ML and Haskell?
◦ (Note: Java 5 has many but not all of the above features)
A brief history of fun in C#A brief history of fun in C#
 C# 1.0:
◦ First-class functions (delegates), created only from named
methods. Environment=object, code=method.
 C# 2.0:
◦ Parameterized types and polymorphic methods (generics)
◦ Anonymous methods: creation of delegate objects from code
bodies, closure-converted by C# compiler
◦ Iterators: stream abstraction, like generators from Clu
 C# 3.0:
◦ Lambda expressions: lightweight syntax for anonymous
methods whose bodies are expressions
◦ Type inference for locals and lambdas
◦ (Also, not discussed: expression trees for lambdas)
Delegates (C# 1.0)Delegates (C# 1.0)
 Essentially named function types e.g.
delegate bool IntPred(int x);
 Delegate objects capture a method code pointer together with
an object reference e.g.
class Point {
int x; int y;
bool Above(int ybound)
{ return y >= ybound; }
}
Point point;
IntPred predicate = new IntPred(point.Above);
 Compare (environment, code pointer) closure in a functional
language.
Generics (C# 2.0)Generics (C# 2.0)
 Types (classes, interfaces, structs and delegates) can be
parameterized on other types e.g.
delegate R Func<A,R>(A arg);
class List<T> { ... }
class Dict<K,D> { ... }
 Methods (instance and static) can be parameterized on types e.g.
static void Sort<T>(T[] arr);
static void Swap<T>(ref T x, ref T y);
class List<T> {
List<Pair<T,U>> Zip<U>(List<U> other) ..
 Very few restrictions:
◦ Parameterization over primitive types, reference types, structs
◦ Types preserved at runtime, in spirit of the .NET object model
Generics: expressivenessGenerics: expressiveness
1. Polymorphic recursion e.g.
static void Foo<T>(List<T> xs) {
…Foo<List<List<T>>>(…)… }
2. First-class polymorphism (System F) e.g.
interface Sorter { void Sort<T>(T[] arr); }
class QuickSort : Sorter { … }
class MergeSort : Sorter { … }
3. GADTs e.g.
abstract class Expr<T> { T Eval(); }
class Lit : Expr<int> { int Eval() { … } }
class PairExpr<A,B> : Expr<Pair<A,B>>
{ Expr<A> e1; Expr<B> e2; Pair<A,B> Eval() { … } }
Also possible
in Java 5
Anonymous methods (C# 2.0)Anonymous methods (C# 2.0)
 Delegates are clumsy: programmer has to name the function and
“closure-convert” by hand
 So C# 2.0 introduced anonymous methods
◦ No name
◦ Compiler does closure-conversion, creating a class and object that
captures the environment e.g.
bool b = xs.Exists(delegate(int x) { return x>y; });
Local y is free in body of
anonymous method
IEnumerable<T>IEnumerable<T>
 Like Java, C# provides interfaces that abstract the ability to
enumerate a collection:
interface IEnumerable<T>
{ IEnumerator<T> GetEnumerator(); }
interface IEnumerator<T> {
T Current { get; }
bool MoveNext();
}
 To “consume” an enumerable collection, we can use the foreach
construct:
foreach (int x in xs) { Console.WriteLine(x); }
 But in C# 1.0, implementing the “producer” side was error-prone
(must implement Current and MoveNext methods)
Iterators (C# 2.0)Iterators (C# 2.0)
 C# 2.0 introduces iterators, easing task of implementing
IEnumerable e.g.
static IEnumerable<int> UpAndDown(int bottom, int top) {
for (int i = bottom; i < top; i++) { yield return i; }
for (int j = top; j >= bottom; j--) { yield return j; }
}
 Iterators can mimic functional-style streams.They can be infinite:
static IEnumerable<int> Evens() {
for (int i = 0; true; i += 2) { yield return i; } }
 The System.Query library provides higher-order functions on
IEnumerable<T> for map, filter, fold, append, drop, take, etc.
static IEnumerable<T> Drop(IEnumerable<T> xs, int n) {
foreach(T x in xs) { if (n>0) n--; else yield return x; }}
Lambda expressionsLambda expressions
 Anonymous methods are just a little too heavy compared with
lambdas in Haskell or ML: compare
delegate (int x, int y) { return x*x + y*y; }
(x,y) -> x*x + y*y
fn (x,y) => x*x + y*y
 C# 3.0 introduces lambda expressions with a lighter syntax,
inference (sometimes) of argument types, and expression bodies:
(x,y) => x*x + y*y
 Language specification simply defines lambdas by translation to
anonymous methods.
Type inference (C# 3.0)Type inference (C# 3.0)
 Introduction of generics in C# 2.0, and absence of type aliases,
leads to typefull programs!
Dict<string,Func<int,Set<int>>> d = new
Dict<string,Func<int,Set<int>>>();
Func<int,int,int> f = delegate (int x, int y) { return x*x + y*y; }
 C# 3.0 supports a modicum of type inference for local variables
and lambda arguments:
var d = new Dict<string,Func<int,Set<int>>>();
Func<int,int,int> f = (x,y) => x*x + y*y;
GADTsGADTs
 Generalized Algebraic DataTypes permit constructors to return
different instantiations of the defined type
 Canonical example is well-typed expressions e.g.
datatype Expr a with
Lit : int → Expr int
| PairExpr : Expr a → Expr b → Expr (a £ b)
| Fst : Expr (a £ b) → Expr a …
 In C#, we can render this using “polymorphic inheritance”:
abstract class Expr<a>
class Lit : Expr<int> { int val; … }
class PairExpr<a,b> : Expr<Pair<a,b>> { Expr<a> e1; Expr<b> e2; … }
class Fst<a,b> : Expr<a> { Expr<Pair<a,b>> e; … }
 Demo: strongly-typed printf
ImplementationImplementation
 C# is compiled to IL, an Intermediate Language that is
executed on the .NET Common Language Runtime
 The CLR has direct support for many of the features
described here
◦ Delegates are special classes with fast calling convention
◦ Generics (parametric polymorphism) is implemented by just-in-
time specialization so no boxing is required
◦ Closure conversion is done by the C# compiler, which shares
environments between closures where possible
Putting it togetherPutting it together
1. Take your favourite functional pearl
2. Render it in C# 3.0
 Here, Hutton & Meijer’s monadic parser combinators.
Demo.
Fun in C#: serious competition?Fun in C#: serious competition?
 It’s functional programming bolted onto a determinedly imperative
object-oriented language
◦ Quite nicely done, but C# 3.0 shows its history
◦ The additional features in C# 3.0 were driven by the LINQ project
(Language INtegrated Query)
 Contrast Scala, which started with (almost) a clean slate:
◦ Object-oriented programming (new design) + functional programming
(new design)
 Many features remain the preserve of functional languages
◦ Datatypes & pattern matching
◦ Higher-kinded types, existentials, sophisticated modules
◦ Unification/constraint-based type inference
◦ True laziness
Closures might surprise you...Closures might surprise you...
 Why? Clue: r-values vs l-values. Arguably, the right design:
static void While(VoidFunc<bool> condition,VoidFunc action) { … }
int x = 1;While(() => x < 10, () => { x=2*x; });
var funs = new Func<int,int>[5]; // Array of functions of type int→int
for (int i = 0; i<5; i++)
{
funs[i] = j => i+j; // To position index i, assign λj. i+j
}
Console.WriteLine(funs[1](2));
 Guess the output
Result is “7”!
Iterators might surprise you…Iterators might surprise you…
 Iterator combinators can be defined purely using foreach and yield.
X Head<X>(IEnumerable<X> xs)
{ foreach (X x in xs) { return x; } }
IEnumerable<X> Tail<X>(IEnumerable<X> xs)
{ bool head = true;
foreach (X x in xs) { if (head) head = false; else yield return x; } }
 But performance implications are surprising:
IEnumerable<int> xs;
for (int i = 0; i < n; i++) { xs = Tail(xs); }
int v = Head(xs);
Cost is O(n2
)!
PerformancePerformance
 Closure creation and application are relatively cheap
operations
◦ But almost no optimizations are performed. Contrast
ML/Haskell uncurrying, arity-raising, flow analysis, etc.
 Iterators are not lazy streams
◦ No memoizing of results
◦ Chaining of IEnumerable wrappers can lead to worsening of
asymptotic complexity
◦ Though there’s nothing to prevent the programmer
implementing a proper streams library, as in ML
Try it yourselfTry it yourself
 C# 2.0 is part of .NET Framework 2.0 SDK available
free from
http://msdn.microsoft.com/downloads/
 Also Visual C# Express Edition: a free lightweight
version of Visual Studio
http://msdn.microsoft.com/vstudio/express/visualcsharp/
 Download preview of C# 3.0 from
http://msdn.microsoft.com/data/ref/linq/

More Related Content

What's hot

DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScriptAleš Najmann
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++HalaiHansaika
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
API design: using type classes and dependent types
API design: using type classes and dependent typesAPI design: using type classes and dependent types
API design: using type classes and dependent typesbmlever
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slidesOCaml
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?Andreas Enbohm
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 

What's hot (19)

Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
API design: using type classes and dependent types
API design: using type classes and dependent typesAPI design: using type classes and dependent types
API design: using type classes and dependent types
 
C++ 11
C++ 11C++ 11
C++ 11
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
C++ oop
C++ oopC++ oop
C++ oop
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 

Similar to C# Functional Programming Features

The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#singhadarsh
 

Similar to C# Functional Programming Features (20)

Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Python basic
Python basicPython basic
Python basic
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Clojure intro
Clojure introClojure intro
Clojure intro
 

Recently uploaded

Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...gurkirankumar98700
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...wdefrd
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...gurkirankumar98700
 
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...anilsa9823
 
Akola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service AkolaAkola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service Akolasrsj9000
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiMalviyaNagarCallGirl
 
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...anilsa9823
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...akbard9823
 
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...anilsa9823
 
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...home
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room servicediscovermytutordmt
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhisoniya singh
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...akbard9823
 
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Servicesonnydelhi1992
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...anilsa9823
 
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service HisarVip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisarsrsj9000
 
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiMalviyaNagarCallGirl
 
Call Girl Service In Dubai #$# O56521286O #$# Dubai Call Girls
Call Girl Service In Dubai #$# O56521286O #$# Dubai Call GirlsCall Girl Service In Dubai #$# O56521286O #$# Dubai Call Girls
Call Girl Service In Dubai #$# O56521286O #$# Dubai Call Girlsparisharma5056
 

Recently uploaded (20)

Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
 
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
 
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
 
Akola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service AkolaAkola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service Akola
 
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
 
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
 
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
 
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
 
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
 
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service HisarVip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
 
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
 
Call Girl Service In Dubai #$# O56521286O #$# Dubai Call Girls
Call Girl Service In Dubai #$# O56521286O #$# Dubai Call GirlsCall Girl Service In Dubai #$# O56521286O #$# Dubai Call Girls
Call Girl Service In Dubai #$# O56521286O #$# Dubai Call Girls
 

C# Functional Programming Features

  • 1. C# is a functionalC# is a functional programming languageprogramming language Andrew Kennedy Microsoft Research Cambridge
  • 2. Quicksort revisitedQuicksort revisited Func<intlist, intlist> Sort = xs => xs.Case( () => xs, (head,tail) => (Sort(tail.Where(x => x < head))) .Concat (Single(head)) .Concat (Sort(tail.Where(x => x >= head))) ); Name the language... C# 3.0 type inference append higher-order function parameterized type of functions recursion filter lambda expression
  • 3. The gap narrows...The gap narrows...  C# 3.0 has many features well-known to functional programmers ◦ Parameterized types and polymorphic functions (generics) ◦ First-class functions (delegates) ◦ Lightweight lambda expressions & closure conversion ◦ Type inference (for locals and lambdas) ◦ Streams (iterators) ◦ A library of higher-order functions for collections & iterators ◦ And even: GADTs (polymorphic inheritance)  This talk: is it serious competition for ML and Haskell? ◦ (Note: Java 5 has many but not all of the above features)
  • 4. A brief history of fun in C#A brief history of fun in C#  C# 1.0: ◦ First-class functions (delegates), created only from named methods. Environment=object, code=method.  C# 2.0: ◦ Parameterized types and polymorphic methods (generics) ◦ Anonymous methods: creation of delegate objects from code bodies, closure-converted by C# compiler ◦ Iterators: stream abstraction, like generators from Clu  C# 3.0: ◦ Lambda expressions: lightweight syntax for anonymous methods whose bodies are expressions ◦ Type inference for locals and lambdas ◦ (Also, not discussed: expression trees for lambdas)
  • 5. Delegates (C# 1.0)Delegates (C# 1.0)  Essentially named function types e.g. delegate bool IntPred(int x);  Delegate objects capture a method code pointer together with an object reference e.g. class Point { int x; int y; bool Above(int ybound) { return y >= ybound; } } Point point; IntPred predicate = new IntPred(point.Above);  Compare (environment, code pointer) closure in a functional language.
  • 6. Generics (C# 2.0)Generics (C# 2.0)  Types (classes, interfaces, structs and delegates) can be parameterized on other types e.g. delegate R Func<A,R>(A arg); class List<T> { ... } class Dict<K,D> { ... }  Methods (instance and static) can be parameterized on types e.g. static void Sort<T>(T[] arr); static void Swap<T>(ref T x, ref T y); class List<T> { List<Pair<T,U>> Zip<U>(List<U> other) ..  Very few restrictions: ◦ Parameterization over primitive types, reference types, structs ◦ Types preserved at runtime, in spirit of the .NET object model
  • 7. Generics: expressivenessGenerics: expressiveness 1. Polymorphic recursion e.g. static void Foo<T>(List<T> xs) { …Foo<List<List<T>>>(…)… } 2. First-class polymorphism (System F) e.g. interface Sorter { void Sort<T>(T[] arr); } class QuickSort : Sorter { … } class MergeSort : Sorter { … } 3. GADTs e.g. abstract class Expr<T> { T Eval(); } class Lit : Expr<int> { int Eval() { … } } class PairExpr<A,B> : Expr<Pair<A,B>> { Expr<A> e1; Expr<B> e2; Pair<A,B> Eval() { … } } Also possible in Java 5
  • 8. Anonymous methods (C# 2.0)Anonymous methods (C# 2.0)  Delegates are clumsy: programmer has to name the function and “closure-convert” by hand  So C# 2.0 introduced anonymous methods ◦ No name ◦ Compiler does closure-conversion, creating a class and object that captures the environment e.g. bool b = xs.Exists(delegate(int x) { return x>y; }); Local y is free in body of anonymous method
  • 9. IEnumerable<T>IEnumerable<T>  Like Java, C# provides interfaces that abstract the ability to enumerate a collection: interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<T> { T Current { get; } bool MoveNext(); }  To “consume” an enumerable collection, we can use the foreach construct: foreach (int x in xs) { Console.WriteLine(x); }  But in C# 1.0, implementing the “producer” side was error-prone (must implement Current and MoveNext methods)
  • 10. Iterators (C# 2.0)Iterators (C# 2.0)  C# 2.0 introduces iterators, easing task of implementing IEnumerable e.g. static IEnumerable<int> UpAndDown(int bottom, int top) { for (int i = bottom; i < top; i++) { yield return i; } for (int j = top; j >= bottom; j--) { yield return j; } }  Iterators can mimic functional-style streams.They can be infinite: static IEnumerable<int> Evens() { for (int i = 0; true; i += 2) { yield return i; } }  The System.Query library provides higher-order functions on IEnumerable<T> for map, filter, fold, append, drop, take, etc. static IEnumerable<T> Drop(IEnumerable<T> xs, int n) { foreach(T x in xs) { if (n>0) n--; else yield return x; }}
  • 11. Lambda expressionsLambda expressions  Anonymous methods are just a little too heavy compared with lambdas in Haskell or ML: compare delegate (int x, int y) { return x*x + y*y; } (x,y) -> x*x + y*y fn (x,y) => x*x + y*y  C# 3.0 introduces lambda expressions with a lighter syntax, inference (sometimes) of argument types, and expression bodies: (x,y) => x*x + y*y  Language specification simply defines lambdas by translation to anonymous methods.
  • 12. Type inference (C# 3.0)Type inference (C# 3.0)  Introduction of generics in C# 2.0, and absence of type aliases, leads to typefull programs! Dict<string,Func<int,Set<int>>> d = new Dict<string,Func<int,Set<int>>>(); Func<int,int,int> f = delegate (int x, int y) { return x*x + y*y; }  C# 3.0 supports a modicum of type inference for local variables and lambda arguments: var d = new Dict<string,Func<int,Set<int>>>(); Func<int,int,int> f = (x,y) => x*x + y*y;
  • 13. GADTsGADTs  Generalized Algebraic DataTypes permit constructors to return different instantiations of the defined type  Canonical example is well-typed expressions e.g. datatype Expr a with Lit : int → Expr int | PairExpr : Expr a → Expr b → Expr (a £ b) | Fst : Expr (a £ b) → Expr a …  In C#, we can render this using “polymorphic inheritance”: abstract class Expr<a> class Lit : Expr<int> { int val; … } class PairExpr<a,b> : Expr<Pair<a,b>> { Expr<a> e1; Expr<b> e2; … } class Fst<a,b> : Expr<a> { Expr<Pair<a,b>> e; … }  Demo: strongly-typed printf
  • 14. ImplementationImplementation  C# is compiled to IL, an Intermediate Language that is executed on the .NET Common Language Runtime  The CLR has direct support for many of the features described here ◦ Delegates are special classes with fast calling convention ◦ Generics (parametric polymorphism) is implemented by just-in- time specialization so no boxing is required ◦ Closure conversion is done by the C# compiler, which shares environments between closures where possible
  • 15. Putting it togetherPutting it together 1. Take your favourite functional pearl 2. Render it in C# 3.0  Here, Hutton & Meijer’s monadic parser combinators. Demo.
  • 16. Fun in C#: serious competition?Fun in C#: serious competition?  It’s functional programming bolted onto a determinedly imperative object-oriented language ◦ Quite nicely done, but C# 3.0 shows its history ◦ The additional features in C# 3.0 were driven by the LINQ project (Language INtegrated Query)  Contrast Scala, which started with (almost) a clean slate: ◦ Object-oriented programming (new design) + functional programming (new design)  Many features remain the preserve of functional languages ◦ Datatypes & pattern matching ◦ Higher-kinded types, existentials, sophisticated modules ◦ Unification/constraint-based type inference ◦ True laziness
  • 17. Closures might surprise you...Closures might surprise you...  Why? Clue: r-values vs l-values. Arguably, the right design: static void While(VoidFunc<bool> condition,VoidFunc action) { … } int x = 1;While(() => x < 10, () => { x=2*x; }); var funs = new Func<int,int>[5]; // Array of functions of type int→int for (int i = 0; i<5; i++) { funs[i] = j => i+j; // To position index i, assign λj. i+j } Console.WriteLine(funs[1](2));  Guess the output Result is “7”!
  • 18. Iterators might surprise you…Iterators might surprise you…  Iterator combinators can be defined purely using foreach and yield. X Head<X>(IEnumerable<X> xs) { foreach (X x in xs) { return x; } } IEnumerable<X> Tail<X>(IEnumerable<X> xs) { bool head = true; foreach (X x in xs) { if (head) head = false; else yield return x; } }  But performance implications are surprising: IEnumerable<int> xs; for (int i = 0; i < n; i++) { xs = Tail(xs); } int v = Head(xs); Cost is O(n2 )!
  • 19. PerformancePerformance  Closure creation and application are relatively cheap operations ◦ But almost no optimizations are performed. Contrast ML/Haskell uncurrying, arity-raising, flow analysis, etc.  Iterators are not lazy streams ◦ No memoizing of results ◦ Chaining of IEnumerable wrappers can lead to worsening of asymptotic complexity ◦ Though there’s nothing to prevent the programmer implementing a proper streams library, as in ML
  • 20. Try it yourselfTry it yourself  C# 2.0 is part of .NET Framework 2.0 SDK available free from http://msdn.microsoft.com/downloads/  Also Visual C# Express Edition: a free lightweight version of Visual Studio http://msdn.microsoft.com/vstudio/express/visualcsharp/  Download preview of C# 3.0 from http://msdn.microsoft.com/data/ref/linq/