Higher order functions in C#

C# is not a functional language


...but it is a gateway drug to functional programming.

 ready?


first class functions


functions can be assigned to variables

to be passed around

at a language level


Does [language] support first-class functions?

does c# support first-class functions?

YES


higher-order functions




a function that brings in a function

a function that returns a function

at a function level


Is this a higher-order function?

c# 2 (2005)


generics
anonymous methods
delegates

C# 3 (2007)


type inference
anonymous types
extension methods
lambdas
expressions


first-class things

public void DoSomethingWithFruit()
{ int numberOfApples = 6; DoSomethingWithApples(numberOfApples);}

public void MakePie(string flavour)
{ UseFlavour(flavour);}
string pieFlavour = "Steak n Cheese";MakePie(pieFlavour);

action


A class that represents a function

public void WhistleJauntyTune(){    // let the whistling commence...}
Action whistle = WhistleJauntyTune;
// call the actionwhistle();

action<t>


Arguments!

public void JumpAround(int numberOfTimes){    // jump up jump up and get down}
Action<int> jump = JumpAround;jump(17);

action<t1, t2, ...>


As argumentative as you like!

public void Something(int i, string s, double d){    // something something all the things...}
var something = Something;something(1, "1", 1.0);

Func<t>


For returning things

public int TheAnswer(){    return 42;}
Func<int> answer = TheAnswer;var a = answer();

func<t, tR>


TR: Response Type

public string DoThisThing(int number){    return number.ToString();}
Func<int, string> thisThing = DoThisThing;string s = thisThing(3); // s == "3"

demo


The rest of the talk was in VS
Made with Slides.com