Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Manipulating functions in functional programming

Save for later
  • 6 min read
  • 20 Jun 2017

article-image

In this article by Wisnu Anggoro, author of the book Learning C++ Functional Programming, you will learn to apply functional programming techniques to C++ to build highly modular, testable, and reusable code.

In this article, you will learn the following topics:

  • Applying a first-class function in all functions
  • Passing a function as other functions parameter
  • Assigning a function to a variable
  • Storing a function in the container

(For more resources related to this topic, see here.)

Applying a first-class function in all functions

There's nothing special with the first-class function since it's a normal class. We can treat the first-class function like any other data type. However, in the language that supports the first-class function, we can perform the following tasks without invoking the compiler recursively:

  • Passing a function as other function parameters
  • Assigning functions to a variable
  • Storing functions in collections

Fortunately, C++ can be used to solve the preceding tasks. We will discuss it in depth in the following topics.

Passing a function as other functions parameter

Let's start passing a function as the function parameter. We will choose one of four functions and invoke the function from its main function. The code will look as follows:

/* first-class-1.cpp */
    #include <functional>
    #include <iostream>


    using namespace std;


    typedef function<int(int, int)> FuncType;


    int addition(int x, int y)
    {
      return x + y;
    }


    int subtraction(int x, int y)
    {
      return x - y;
    }


    int multiplication(int x, int y)
    {
      return x * y;
    }


    int division(int x, int y)
    {
      return x / y;
    }


    void PassingFunc(FuncType fn, int x, int y)
    {
      cout << "Result = " << fn(x, y) << endl;
    }


    int main()
    {
      int i, a, b;
      FuncType func;


      cout << "Select mode:" << endl;
      cout << "1. Addition" << endl;
      cout << "2. Subtraction" << endl;
      cout << "3. Multiplication" << endl;
      cout << "4. Division" << endl;
      cout << "Choice: ";
      cin >> i;


      cout << "a = ";
      cin >> a;


      cout << "b = ";
      cin >> b;


      switch(i)
      {
        case 1: PassingFunc(addition, a, b); break;
        case 2: PassingFunc(subtraction, a, b); break;
        case 3: PassingFunc(multiplication, a, b); break;
        case 4: PassingFunc(division, a, b); break;
      }


      return 0;
    }

From the preceding code, we can see that we have four functions, and we want the user to choose one from them, and then run it. In the switch statement, we will invoke one of the four functions based on the choice of the user. We will pass the selected function to PassingFunc(), as we can see in the following code snippet:

    case 1: PassingFunc(addition, a, b); break;
    case 2: PassingFunc(subtraction, a, b); break;
    case 3: PassingFunc(multiplication, a, b); break;
    case 4: PassingFunc(division, a, b); break;

The result we get on the screen should look like the following screenshot:

manipulating-functions-functional-programming-img-0

The preceding screenshot shows that we selected the Subtraction mode and gave 8 to a and 3 to b. As we expected, the code gives us 5 as a result.

Assigning a function to variable

We can also assign a function to the variable so that we can call the function by calling the variable. We will refactor first-class-1.cpp, and it will be as follows:

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at R$50/month. Cancel anytime
/* first-class-2.cpp */
    #include <functional>
    #include <iostream>


    using namespace std;


    // Adding the addition, subtraction, multiplication,
       and
    // division function as we've got in first-class-1.cpp


    int main()
    {
      int i, a, b;
      function<int(int, int)> func;


      cout << "Select mode:" << endl;
      cout << "1. Addition" << endl;
      cout << "2. Subtraction" << endl;
      cout << "3. Multiplication" << endl;
      cout << "4. Division" << endl;
      cout << "Choice: ";
      cin >> i;


      cout << "a = ";
      cin >> a;


      cout << "b = ";
      cin >> b;


      switch(i)
      {
        case 1: func = addition; break;
        case 2: func = subtraction; break;
        case 3: func = multiplication; break;
        case 4: func = division; break;
      }


      cout << "Result = " << func(a, b) << endl;


      return 0;
    }

We will now assign the four functions based on the user choice. We will store the selected function in func variable inside the switch statement, as follows:

    case 1: func = addition; break;
    case 2: func = subtraction; break;
    case 3: func = multiplication; break;
    case 4: func = division; break;

After the func variable is assigned with the user's choice, the code will just call the variable like calling the function as follows:

cout << "Result = " << func(a, b) << endl;

Moreover, we will obtain the same output on the console if we run the code.

Storing a function in the container

Now, let's save the function to the container. Here, we will use the vector as the container. The code is as follows:

/* first-class-3.cpp */
    #include <vector>
    #include <functional>
    #include <iostream>


    using namespace std;


    typedef function<int(int, int)> FuncType;


    // Adding the addition, subtraction, multiplication, 
       and
    // division function as we've got in first-class-1.cpp


    int main()
    {
      vector<FuncType> functions;


      functions.push_back(addition);
      functions.push_back(subtraction);
      functions.push_back(multiplication);
      functions.push_back(division);


      int i, a, b;
      function<int(int, int)> func;


      cout << "Select mode:" << endl;
      cout << "1. Addition" << endl;
      cout << "2. Subtraction" << endl;
      cout << "3. Multiplication" << endl;
      cout << "4. Division" << endl;
      cout << "Choice: ";
      cin >> i;


      cout << "a = ";
      cin >> a;


      cout << "b = ";
      cin >> b;


      cout << "Result = " << functions.at(i - 1)(a, b) << endl;


      return 0;
    }

From the preceding code, we can see that we created a new vector named functions, then stored four different functions to it. Same with our two previous code samples, we ask the user to select the mode as well. However, now the code becomes simpler since we don't need to add the switch statement as we can select the function directly by selecting the vector index, as we can see in the following line of code:

cout << "Result = " << functions.at(i - 1)(a, b) << endl;

However, since the vector is a zero-based index, we have to adjust the index with the menu choice. The result will be the same with our two previous code samples.

Summary

In this article, we discussed that there are some techniques to manipulate a function to produce the various purpose on it. Since we can implement the first-class function in C++ language, we can pass a function as other functions parameter. We can treat a function as a data object so we can assign it to a variable and store it in the container.

Resources for Article:


Further resources on this subject: