Subject: phoenix lambda-lambda for_each example
From: Joel de Guzman <[email-masked]>
To: Noah Stein <[email-masked]>
Cc: [email-masked], David Abrahams <[email-masked]>, Aleksey Gurtovoy <[email-masked]>, Jaakko Jarvi <[email-masked]>
Date: Wed, 03 Mar 2004 10:21:10 +0800

Hi,

<shameless plug>

    phoenix is rockin' rollin cool :-)

</shameless plug>

It's extensibility has proven itself time and again. Already,
we have lazy versions of almost all STL sequence functions
such as push_back, insert, remove, etc. Angus Leeming implemented
them, after learning the library in a couple of days!

Example usage:

     push_back(arg1, back(arg1)+1)

Now, the algorithms...

I took a few minutes to write a lazy for_each.

Consider this:

     std::vector<std::vector<int> > v;
     ...
     for_each(arg1, for_each(arg1, cout << arg1 << ' '))
     (v);

Prints all the elements of v.

Cool? I would say ROCKIN' !!!

See attached. We'll be seeing a full lazy STL very soon! Noah Stein
will be working on it. Noah? :-)

Regards,
-- 
Joel de Guzman
http://www.boost-consulting.com
http://spirit.sf.net

#include <boost/spirit/phoenix.hpp>
#include <vector>
#include <iostream>
#include <algorithm>

namespace phoenix
{
    struct for_each_impl
    {
        template <typename C, typename F>
        struct result { typedef void type; };

        template <typename C, typename F>
        void operator()(C& c, F f)
        {
            std::for_each(c.begin(), c.end(), f);
        }
    };

    template <typename C, typename F>
    inline typename impl::make_composite<for_each_impl, C, actor<value<F> > >::type
    for_each(C const& c, F f)
    {
        typedef
            typename impl::make_composite<
                for_each_impl, C, actor<value<F> > >::composite_type
        ret_t;

        return ret_t(
            for_each_impl(),
            as_actor<C>::convert(c),
            value<F>(f)
        );
    }
}

int
main()
{
    int v_[] = { 1, 2, 3, 4, 5 };
    std::vector<std::vector<int> > v;
    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 5; ++j)
            v_[j] *= 2;
        v.push_back(std::vector<int>(v_, v_+5));
    }

    using namespace phoenix;
    namespace phx = phoenix;
    using namespace std;

    phx::for_each(arg1, phx::for_each(arg1, cout << arg1 << ' '))
    (v);
}