SlideShare a Scribd company logo
C# programming
 Name the language...
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)))
);
C# 3.0
type
inference
append
higher-order function
parameterized type of functions
recursion
filter
lambda expression
 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)
 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)
 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.
 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
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
 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
 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)
 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; }}
 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.
 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;
 Generalized Algebraic Data Types 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
 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
1. Take your favourite functional pearl
2. Render it in C# 3.0
 Here, Hutton & Meijer’s monadic parser combinators.
Demo.
 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
 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”!
 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
)!
 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

More Related Content

What's hot (20)

PPTX
Java generics
Hosein Zare
 
PDF
First-Class Patterns
John De Goes
 
PDF
Programming in Scala: Notes
Roberto Casadei
 
PDF
Functional programming ii
Prashant Kalkar
 
PDF
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
PDF
Hey! There's OCaml in my Rust!
Kel Cecil
 
PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
PPT
OOP Core Concept
Rays Technologies
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
Functional programming
Prashant Kalkar
 
PDF
Introduction to functional programming using Ocaml
pramode_ce
 
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
PPTX
The Style of C++ 11
Sasha Goldshtein
 
PPTX
constructors and destructors in c++
HalaiHansaika
 
PDF
Suit case class
Didier Plaindoux
 
PPSX
DITEC - Programming with C#.NET
Rasan Samarasinghe
 
PDF
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
PDF
Functional programming in Scala
Damian Jureczko
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PPT
Python part2 v1
Sunil OS
 
Java generics
Hosein Zare
 
First-Class Patterns
John De Goes
 
Programming in Scala: Notes
Roberto Casadei
 
Functional programming ii
Prashant Kalkar
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Hey! There's OCaml in my Rust!
Kel Cecil
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
OOP Core Concept
Rays Technologies
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Functional programming
Prashant Kalkar
 
Introduction to functional programming using Ocaml
pramode_ce
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
The Style of C++ 11
Sasha Goldshtein
 
constructors and destructors in c++
HalaiHansaika
 
Suit case class
Didier Plaindoux
 
DITEC - Programming with C#.NET
Rasan Samarasinghe
 
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Functional programming in Scala
Damian Jureczko
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Python part2 v1
Sunil OS
 

Viewers also liked (20)

PPTX
Actividad8 140343 139885
tania
 
PDF
Actividad 8 analisis tendencia pedagógica. carlos andrés estupiñan iglesias
Carlos Iglesias
 
PPT
Gpc parto msp
Leonidas Brito
 
PPT
MT Network
tsumuraya
 
PDF
Strategic & Opportunistic Development Plans for Hotels
The Innova Room
 
PDF
El contenido es el rey, Paco Nadal (El Viajero-El País)
EscapadaRural
 
PPTX
Taller sobre Marca Personal en eTalentDays
Ferran Calatayud
 
PDF
Demanda ignacio gutiérrez
Patricio Alejandro Gutierrez Villagran
 
PPTX
Juan Ángel Martínez
EscapadaRural
 
PDF
Dissertation Economic and Financial Impact Of Event Tourism on Dubai
Solve My Assignment
 
PDF
Las misiones guaraníes de los jesuitas
Manu Pérez
 
PDF
Norma oficial mexicana nom 007-ssa2-2016 para la atención de la mujer durante...
susana hernandez
 
PDF
Imagen y posicionamiento de la ciudad de La Plata
Santiago Cravero Igarza
 
PDF
DISEÑO DE PISOS
rogelio01
 
PDF
Auditoria Social Media
Loreto GF
 
PPTX
Santo Tomas de Aquino
Alejandra Gómez Huamán
 
PDF
Los diez mandamientos de la ensenanza tracey-tokuhama-espinosa
Ministerio de Educación
 
PPSX
Presentación1
alexmihermano
 
PDF
Marketing Digital
Leticia Eugenio
 
PPTX
Comercializar Turismo Rural por Internet
Turismo Rural
 
Actividad8 140343 139885
tania
 
Actividad 8 analisis tendencia pedagógica. carlos andrés estupiñan iglesias
Carlos Iglesias
 
Gpc parto msp
Leonidas Brito
 
MT Network
tsumuraya
 
Strategic & Opportunistic Development Plans for Hotels
The Innova Room
 
El contenido es el rey, Paco Nadal (El Viajero-El País)
EscapadaRural
 
Taller sobre Marca Personal en eTalentDays
Ferran Calatayud
 
Demanda ignacio gutiérrez
Patricio Alejandro Gutierrez Villagran
 
Juan Ángel Martínez
EscapadaRural
 
Dissertation Economic and Financial Impact Of Event Tourism on Dubai
Solve My Assignment
 
Las misiones guaraníes de los jesuitas
Manu Pérez
 
Norma oficial mexicana nom 007-ssa2-2016 para la atención de la mujer durante...
susana hernandez
 
Imagen y posicionamiento de la ciudad de La Plata
Santiago Cravero Igarza
 
DISEÑO DE PISOS
rogelio01
 
Auditoria Social Media
Loreto GF
 
Santo Tomas de Aquino
Alejandra Gómez Huamán
 
Los diez mandamientos de la ensenanza tracey-tokuhama-espinosa
Ministerio de Educación
 
Presentación1
alexmihermano
 
Marketing Digital
Leticia Eugenio
 
Comercializar Turismo Rural por Internet
Turismo Rural
 
Ad

Similar to C# programming (20)

PDF
C# quick ref (bruce 2016)
Bruce Hantover
 
PPTX
2. overview of c#
Rohit Rao
 
PPTX
C#.net Evolution part 1
Vahid Farahmandian
 
ODP
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
PDF
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
PPTX
.Net Framework 2 fundamentals
Harshana Weerasinghe
 
PPT
Introduction to csharp
hmanjarawala
 
PPT
Introduction to csharp
voegtu
 
PPT
Introduction to csharp
voegtu
 
PPT
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
PPT
Introduction-to-Csharp programacion orientada a objetos
KilbertChusiHuamani
 
PPT
Introduction-to-Csharp.ppt
Almamoon
 
PPT
Introduction-to-Csharp.ppt
mothertheressa
 
PPT
Introduction to-csharp
SDFG5
 
PPT
03 oo with-c-sharp
Naved khan
 
PPTX
Linq Introduction
Neeraj Kaushik
 
PPTX
PDC Video on C# 4.0 Futures
nithinmohantk
 
PPTX
C# - Igor Ralić
Software StartUp Academy Osijek
 
PPT
Generics collections
Yaswanth Babu Gummadivelli
 
C# quick ref (bruce 2016)
Bruce Hantover
 
2. overview of c#
Rohit Rao
 
C#.net Evolution part 1
Vahid Farahmandian
 
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
.Net Framework 2 fundamentals
Harshana Weerasinghe
 
Introduction to csharp
hmanjarawala
 
Introduction to csharp
voegtu
 
Introduction to csharp
voegtu
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
Introduction-to-Csharp programacion orientada a objetos
KilbertChusiHuamani
 
Introduction-to-Csharp.ppt
Almamoon
 
Introduction-to-Csharp.ppt
mothertheressa
 
Introduction to-csharp
SDFG5
 
03 oo with-c-sharp
Naved khan
 
Linq Introduction
Neeraj Kaushik
 
PDC Video on C# 4.0 Futures
nithinmohantk
 
Generics collections
Yaswanth Babu Gummadivelli
 
Ad

More from umesh patil (20)

PPTX
Ccna security
umesh patil
 
PPTX
Array in c language
umesh patil
 
PPTX
Array in c language
umesh patil
 
PPTX
Jquery Preparation
umesh patil
 
PPTX
Cloud computing
umesh patil
 
PPT
Static and dynamic polymorphism
umesh patil
 
PPTX
Introduction to asp .net
umesh patil
 
PPTX
C language
umesh patil
 
PPTX
Html and css presentation
umesh patil
 
PPTX
Html Presentation
umesh patil
 
PPTX
Cloud computing
umesh patil
 
PPT
Oops and c fundamentals
umesh patil
 
PPT
Java script
umesh patil
 
PPTX
Function in c program
umesh patil
 
PPTX
css and wordpress
umesh patil
 
PPTX
css and wordpress
umesh patil
 
PPTX
Php vs asp
umesh patil
 
PPTX
Ccna security
umesh patil
 
PPT
Cloud computing
umesh patil
 
PPTX
Cloud computing
umesh patil
 
Ccna security
umesh patil
 
Array in c language
umesh patil
 
Array in c language
umesh patil
 
Jquery Preparation
umesh patil
 
Cloud computing
umesh patil
 
Static and dynamic polymorphism
umesh patil
 
Introduction to asp .net
umesh patil
 
C language
umesh patil
 
Html and css presentation
umesh patil
 
Html Presentation
umesh patil
 
Cloud computing
umesh patil
 
Oops and c fundamentals
umesh patil
 
Java script
umesh patil
 
Function in c program
umesh patil
 
css and wordpress
umesh patil
 
css and wordpress
umesh patil
 
Php vs asp
umesh patil
 
Ccna security
umesh patil
 
Cloud computing
umesh patil
 
Cloud computing
umesh patil
 

Recently uploaded (20)

PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 

C# programming

  • 2.  Name the language... 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))) ); C# 3.0 type inference append higher-order function parameterized type of functions recursion filter lambda expression
  • 3.  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.  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.  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.  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. 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.  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.  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.  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.  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.  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.  Generalized Algebraic Data Types 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.  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. 1. Take your favourite functional pearl 2. Render it in C# 3.0  Here, Hutton & Meijer’s monadic parser combinators. Demo.
  • 16.  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.  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.  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.  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