Chapter 5. Higher-Order Functions
Welcome back, my friends, to the show that never ends. In this chapter, we’ll look at uses for higher-order functions. I’m going to show you novel ways to use them in C# to save yourself effort and to make code that is less likely to fail.
But, what are higher-order functions? This slightly odd name represents something very simple. In fact, you’ve likely been using higher-order functions for some time if you’ve spent much time working with LINQ. They come in two flavors; here’s the first:
varliberatorCrew=new[]{"Roj Blake","Kerr Avon","Vila Restal","Jenna Stannis","Cally","Olag Gan","Zen"};varfilteredList=liberatorCrew.Where(x=>x.First()>'M');
Passed into the Where() function is an arrow expression, which is just shorthand for writing out an unnamed function. The longhand version would look like this:
functionboolIsGreaterThanM(charc){returnc>'m';}
So here, the function has been passed around as the parameter to another function, to be executed elsewhere inside it.
This is another example of the use of higher-order functions:
publicFunc<int,int>MakeAddFunc(intx)=>y=>x+y;
Notice here that there are two arrows, not one. We’re taking an integer x and from that returning a new function. In that new function, references to x will be filled in with whatever was provided when MakeAddFunc() was called originally.
For example:
varaddTenFunction=MakeAddFunc(10);varanswer=addTenFunction(5);// answer is 15 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access