Function composition

If I have f and g the right way around then the following should be satisfied:

compose( f, g )( x ) == f( g( x ) )

It should also be possible to do this with Boost.Bind.

By Kirit with contributions by nobody yet.

Recipe source code

#include <iostream>

#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>


template< typename R, typename I, typename S >
boost::function< R ( I ) > compose( boost::function< R ( I ) > f, boost::function< I ( S ) > g ) {
    return boost::lambda::bind( f, boost::lambda::bind( g, boost::lambda::_1 ) );
}

template< typename T, typename Y >
boost::function< T > operator *( boost::function< T > f, boost::function< Y > g ) {
    return compose( f, g );
}


int main() {
    using namespace boost::lambda;

    boost::function< int ( int ) > inc( _1 + 1 );
    boost::function< int ( int ) > triple( _1 * 3 );
    boost::function< int ( int ) > square( _1 * _1 );

    std::cout << compose( inc, triple )( 2 ) << " = 2 x 3 + 1" << std::endl;
    std::cout << ( triple * inc )( 2 ) << " = ( 2 + 1 ) x 3" << std::endl;
    std::cout << ( square * square )( 3 ) << " = ( 3 x 3 ) x ( 3 x 3 )" << std::endl;
}

This is not an official Boost site. For more information on Boost please see Boost.org.