Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext
fold
Description

Repeatedly applies binary Polymorphic Function Object f to each element of a sequence and the previous state.

Synopsis
template<
    typename Sequence,
    typename State,
    typename F
    >
typename result_of::fold<Sequence, State, F>::type fold(
    Sequence& seq, State const& initial_state, F const& f);

Table 1.32. Parameters

Parameter Requirement Description
seq A model of Forward Sequence,f(e) must be a valid expression for each element e in seq Operation's argument
initial_state Any type Initial state
f A model of binary Polymorphic Function Object Operation's argument
Expression Semantics
fold(seq, initial_state, f);

Return type: Any type

Semantics: Equivalent to f(eN ....f(e2,f(e1,initial_state))) where e1 ...eN are the elements of seq.

Complexity

Linear, exactly result_of::size<Sequence>::value applications of f.

Header
#include <boost/fusion/algorithm/iteration/fold.hpp>
Example
struct make_string
{
    template<typename T, typename State>
    struct apply
    {
        typedef std::string type;
    };

    template<typename T>
    std::string operator()(const T& t, const std::string& str) const
    {
        return str + boost::lexical_cast<std::string>(t);
    }
};
...
const vector<int,int> vec(1,2);
assert(fold(vec,std::string(""), make_string()) == "12");
Copyright © 2001-2005 Joel de Guzman, Dan Marsden

PrevUpHomeNext