Functional programming in C++. Implementing f(a)(b)(c)

Gigaxel picture Gigaxel · May 4, 2017 · Viewed 9.4k times · Source

I have been getting into the basics of functional programming with C++. I am trying to make a function f(a)(b)(c) that will return a + b + c. I successfully implemented the function f(a)(b) which returns a + b. Here is the code for it:

std::function<double(double)> plus2(double a){
    return[a](double b){return a + b; };
}

I just cannot figure out how to implement the function f(a)(b)(c) which as I previously stated should return a + b + c.

Answer

Jonas picture Jonas · May 4, 2017

You can do it by having your function f return a functor, i.e., an object that implements operator(). Here is one way to do it:

struct sum 
{
    double val;

    sum(double a) : val(a) {}

    sum operator()(double a) { return val + a; }

    operator double() const { return val; }
};

sum f(double a)
{
    return a;
}

Example

Link

int main()
{
    std::cout << f(1)(2)(3)(4) << std::endl;
}

Template version

You can even write a templated version that will let the compiler deduce the type. Try it here.

template <class T>
struct sum 
{
    T val;

    sum(T a) : val(a) {}

    template <class T2>
    auto operator()(T2 a) -> sum<decltype(val + a)> { return val + a; }

    operator T() const { return val; }
};

template <class T>
sum<T> f(T a)
{
    return a;
}

Example

In this example, T will ultimately resolve to double:

std::cout << f(1)(2.5)(3.1f)(4) << std::endl;