2 Getting started with functional programming

 

This chapter covers

  • Understanding higher-order functions
  • Using higher-order functions from the STL
  • Problems with composability of STL algorithms
  • Recursion and tail-call optimization
  • The power of the folding algorithm

The previous chapter showed a few neat examples of how to improve your code by using simpler functional programming techniques. We focused on benefits such as greater code conciseness, correctness, and efficiency, but we haven’t covered the special magic of functional programming languages that lets you write code in that manner.

The truth is, after you look behind the curtain, there’s no magic—just simple concepts with big consequences. The first simple yet far-reaching concept we used in the previous chapter is the ability to pass one function as an argument to an algorithm from the Standard Template Library (STL). The algorithms in the STL are applicable to a multitude of problems mainly because you can customize their behavior.

2.1 Functions taking functions?

The main feature of all functional programming (FP) languages is that functions can be treated like ordinary values. They can be stored into variables, put into collections and structures, passed to other functions as arguments, and returned from other functions as results.

2.2 Examples from the STL

2.2.1 Calculating averages

2.2.2 Folding

2.2.3 String trimming

2.2.4 Partitioning collections based on a predicate

2.2.5 Filtering and transforming

2.3 Composability problems of STL algorithms

2.4 Writing your own higher-order functions

2.4.1 Receiving functions as arguments

2.4.2 Implementing with loops

2.4.3 Recursion and tail-call optimization

2.4.4 Implementing using folds

Summary