2. Thinking in functions

 

This chapter covers

  • Functions in math and in programming
  • Representing functions in C#
  • Leveraging higher-order functions

In Chapter 1, you saw how treating functions as first-class values is one of the tenets of FP. This allows the programmer to up the ante, and write functions that are parameterized by or create other functions. These are called higher-order functions (HOFs); they really raise the level of abstraction in our programs, allowing us to do more with less code.

But before we delve into HOFs, let’s take a step back and see what we mean by functions; what they are both in the mathematical and programming jargon; and the various constructs that C# offers to represent functions.

2.1 What’s a function, anyway?

In this section, I’ll clarify what I mean by function. I’ll start with the mathematical use of the word and then move on to the various language constructs that C# offers to represent functions. This will give you some basic conceptual and practical tools to start to code functionally.

2.1.1 Functions as maps

In mathematics, a function is a map between two sets, respectively called the domain and codomain. That is, given an element from its domain, a function yields an element from its codomain. That’s all there is—it doesn’t matter whether the mapping is based on some formula or is completely arbitrary.

2.1.2 Representing functions in C#

2.2 Higher-order functions

2.2.1 Functions that depend on other functions

2.2.2 Adapter functions

2.2.3 Functions that create other functions

2.3 Using HOFs to avoid duplication

2.4 Exercises

2.5 Summary