4 Creating new functions from the old ones

 

This chapter covers

  • Understanding partial function application
  • Fixing function arguments to specific values with std::bind
  • Using lambdas for partial function application
  • Are all functions in the world unary?
  • Creating functions that operate on collections of items

Most programming paradigms tend to provide a way to increase code reusability. In the object-oriented world, we create classes we can later use in various situations. We can use them directly or combine them to implement more-complex classes. The possibility of breaking complex systems into smaller components that can be used and tested separately is a powerful one.

In the same way that OOP gives you the tools to combine and modify types, the functional programming paradigm gives you ways to easily create new functions by combining the functions we’ve already written, by upgrading specialized functions to cover more-general use cases, or, the other way around, by taking more-general functions and simplifying them to perfectly fit a specific use case.

4.1 Partial function application

4.1.1 A generic way to convert binary functions into unary ones

4.1.2 Using std::bind to bind values to specific function arguments

4.1.3 Reversing the arguments of a binary function

4.1.4 Using std::bind on functions with more arguments

4.1.5 Using lambdas as an alternative for std::bind

4.2 Currying: a different way to look at functions

4.2.1 Creating curried functions the easier way

4.2.2 Using currying with database access

4.2.3 Currying and partial function application

4.3 Function composition

4.4 Function lifting, revisited

4.4.1 Reversing a list of pairs

Summary