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:
var
liberatorCrew
=
new
[]
{
"Roj Blake"
,
"Kerr Avon"
,
"Vila Restal"
,
"Jenna Stannis"
,
"Cally"
,
"Olag Gan"
,
"Zen"
};
var
filteredList
=
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:
function
bool
IsGreaterThanM
(
char
c
)
{
return
c
>
'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:
public
Func
<
int
,
int
>
MakeAddFunc
(
int
x
)
=>
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:
var
addTenFunction
=
MakeAddFunc
(
10
);
var
answer
=
addTenFunction
(
5
);
// answer is 15 ...
Get Functional Programming with C# now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.