c++boostfunctorhigher-order-functions

Linear combination of functions in C++


Let's say we have the following:

// some functions
double f1( double x );
double f2( double x );
double f3( double x );
// coefficients
double c1, c2, c3;
// input variable
double x;

We need to calculate

We could use the direct approach which is

double y = c1*f1(x) + c2*f2(x) + c3*f3(x);  // x is passed 3 times as an argument

but that is not what I am trying to achieve. I need this operation to be performed in functor terms, i.e. with higher-order-functions. In pseudocode it must be something like this:

auto F = c1*f1 + c2*f2 + c3*f3; // resulting functor
double y = F(x);                // one and only passing the x value instead of 3 times

Is there a way I could achieve this with standard C++ library or with Boost, for example Boost.HOF? Or could you advice me another library where this is implemented? It is not necessary for the code to look exactly like this. The main thing is defining and applying arithmetic operations to functions instead of numbers and passing the x value only once.


Solution

  • You may want to have a look at Boost.Phoenix. It lets you write lazy functions and also defines operators on them.

    Given your example, you would be able to write the linear combination as close as possible to the mathematical notation:

    auto x = boost::phoenix::arg_names::arg1;
    double c1 = 0, c2 = 1, c3 = 2;
    
    auto y = c1 * f1(x) + c2 * f2(x) + c3 * f3(x);
    

    After this code, y is a callable taking one argument and lazily computing the targeted linear combination.

    double y1 = y(1);
    double y2 = y(2);
    

    All you need to do for this to work, is make phoenix know about the functions with the following statements:

    BOOST_PHOENIX_ADAPT_FUNCTION(int, f1, f1, 1);
    BOOST_PHOENIX_ADAPT_FUNCTION(int, f2, f2, 1);
    BOOST_PHOENIX_ADAPT_FUNCTION(int, f3, f3, 1);
    

    For a full example, have a look at this live example on godbolt.