Skip to Content
Functional Programming with C#
book

Functional Programming with C#

by Simon J. Painter
September 2023
Intermediate to advanced
325 pages
7h 45m
English
O'Reilly Media, Inc.
Book available
Content preview from Functional Programming with C#

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 ...
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.
Start your free trial

You might also like

Functional Programming in C#

Functional Programming in C#

Enrico Buonanno

Publisher Resources

ISBN: 9781492097068Errata PageSupplemental Content