2

I'd like to use Boost.Phoenix to create a lambda function that consists of a few lines of code and then "returns" a value so I can use it together with std::transform.

Like this:

std::transform(a.begin(), a.end(), b.begin(),
        (
            //Do something complicated here with the elements of a:
            statement1,
            statement2,
            statement3
            //Is there a way to return a value here?
        )
        );

With std::for_each this would work perfectly, but with std::transform it does not compile because the comma operator returns void. How can I return a value from a lambda function like this?


Edit: I changed the code fragment because what I wrote in the first place led to misunderstandings about what I want to do.

AbuBakr
  • 968
  • 2
  • 11
  • 22

2 Answers2

1

No, this isn't possible. From the Boost.Phoenix v2 statement docs:

Unlike lazy functions and lazy operators, lazy statements always return void.

(Note that this same assertion is in the Boost.Phoenix v3 docs as well.)

ildjarn
  • 62,044
  • 9
  • 127
  • 211
1

In functional programming, it's not the intention to change state. However, instead of using for_each, you may use accumulate. Accumulating implies you have a 'starting value' (e.g. m=1,n=0), and a function that 'adds' a value to an output value:

#include <vector>

struct MN { int m, n; 
  MN(int m,int n):m(m),n(n){}
  static MN accumulate( MN accumulator, int value ) {
     return MN( accumulator.m + value, accumulator.n * value );
  }
}; // your 'state'

int main(){
  std::vector<int> v(10,10); // { 10, 10, ... }
  MN result = std::accumulate( v.begin(), v.end(), MN(0,1), MN::accumulate );
  printf("%d %d", result.m, result.n );
}

I'm unfamilar with Phoenix, but probably there is a way to define the MN::accumulate function in terms of it.

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • Maybe I should have made clearer that the code fragment I posted in the first place was just supposed to be an example and has not much to do with my actual problem. My problem involves complicated data structures and `std::transform` is definitively the only standard algorithm I can use. I updated the question to clarify this. – AbuBakr May 25 '11 at 08:32