What is wrong with my Phoenix lambda expression? - c++

I would expect the following example Boost Phoenix expression to compile.
What am I missing?
int plus(int a,int b)
{
return a+b;
}
void main(int argc,char** argc)
{
auto plus_1 = phx::bind(&plus,1,arg1);
auto value = phx::lambda[phx::val(plus_1)(arg1)]()(1);
std::cout << value << std::endl;
}

auto plus_1 = phx::bind(&plus,1,arg1);
After this line, plus_1 is a function object that takes one int argument and adds one to it.
phx::lambda[plus_1(arg1)](1);
Whoops. This isn't going to work because (as we said above) plus_1 is a function object that takes one int argument and adds one to it. Here, you're trying to invoke it with arg1.
It isn't obvious from your code what you expect it to do. Can you clarify?
====EDIT====
I see you've edited the code in your question. Your code is still wrong but for a different reason now. This:
phx::val(plus_1)(arg1)
... uses val to create a nullary function that returns the plus_1 unary function. You then try to invoke the nullary function with arg1. Boom.
Here is code that executes and does (what I believe) you intend:
#include <iostream>
#include <boost/phoenix/phoenix.hpp>
namespace phx = boost::phoenix;
using phx::arg_names::arg1;
int plus(int a,int b)
{
return a+b;
}
int main()
{
auto plus_1 = phx::bind(&plus, 1, arg1);
int value = phx::bind(phx::lambda[plus_1], arg1)(1);
std::cout << value << std::endl;
}
The first bind takes the binary plus and turns it into a unary function with the first argument bound to 1. The second bind creates a new unary function that is equivalent to the first, but it does so by safely wrapping the first function using lambda. Why is that necessary? Consider the code below, which is equivalent, but without the lambda:
// Oops, wrong:
int value = phx::bind(phx::bind(&plus, 1, arg1), arg1)(1);
Notice that arg1 appears twice. All expressions get evaluated from the inside out. First, we'll bind the inner arg1 to 1, then evaluate the inner bind yielding 2, which we then try to bind and invoke. That's not going to work because 2 isn't callable.
The use of lambda creates a scope for the inner arg1 so it isn't eagerly substituted. But like I said, the use of the second bind, which forces the need for lambda, yields a function that is equivalent to the first. So it's needlessly complicated. But maybe it helped you understand about bind, lambda and Phoenix scopes.

It's not clear to me what you're trying to accomplish by using lambda here, but if you just want to call plus_1 with 1 (resulting in 2), it's much simpler than your attempt:
#include <iostream>
#include <boost/phoenix.hpp>
int plus(int a, int b)
{
return a + b;
}
int main()
{
namespace phx = boost::phoenix;
auto plus_1 = phx::bind(plus, 1, phx::arg_names::arg1);
std::cout << plus_1(1) << '\n';
}
Online demo
If this isn't what you're trying to accomplish, then you need to describe what you actually want. :-]

Perhaps this can explain it better.
Phoenix is not magic; it is first and foremost C++. It therefore follows the rules of C++.
phx::bind is a function that returns a function object, an object which has an overloaded operator() that calls the function that was bound. Your first statement stores this object into plus_1.
Given all of this, anytime you have the expression plus_1(...), this is a function call. That's what it is; you are saying that you want to call the overloaded operator() function on the type of that object, and that you are going to pass some values to that function.
It doesn't matter whether that expression is in the middle of a [] or not. phx::lambda cannot make C++ change its rules. It can't make plus_1(...) anything other than an immediate function call. Nor can arg1 make plus_1(...) not an immediate function call.

Related

What is this C++14 construct called which seems to chain lambdas?

This is a follow-up question on this one: Lambda-Over-Lambda in C++14, where the answers explain the code.
It is about a lambda that creates another lambda which when called, calls the passed lambda and passes the return value to the original lambda, thus returning a new instance of the second lambda.
The example shows how this way lambdas can be chained.
Copy from the original question:
#include <cstdio>
auto terminal = [](auto term) // <---------+
{ // |
return [=] (auto func) // | ???
{ // |
return terminal(func(term)); // >---------+
};
};
auto main() -> int
{
auto hello =[](auto s){ fprintf(s,"Hello\n"); return s; };
auto world =[](auto s){ fprintf(s,"World\n"); return s; };
terminal(stdout)
(hello)
(world) ;
return 0;
}
Is there already a name for this construct and if not what should it be called?
Does it resemble constructs in other languages?
Remark: I'm not interested in whether it is actually useful.
I looked around a bit and turns out the main functionality is reordering the function calls as explained in the answers to the original question.
So world(hello(stdout)); is rewritten to terminal(stdout)(hello)(world); which more generally could be written as compose(stdout)(hello)(world);.
In Haskell this would written as world . hello $ stdout and is called function composition.
In clojure it would be (-> stdout hello world) and is called the "thread-first" macro
I think it is only useful with decent partial application which lambdas provide a little bit, so we could have compose(4)([](int x){ return x + 7; })([](int x){ return x * 2; })([](int x){ return x == 22; }); which should return true if my calculation (and blind coding) is any good.
or to emphasize the partial application:
auto add7 = [](int x){ return x + 7; };
auto dbl = [](int x){ return x * 2; };
auto equal22 = [](int x){ return x == 22; };
assert(compose(4)(add7)(dbl)(equals22));
1 major issue with this implementation is probably that the result can't be evaluated because in the end a lambda is returned, so the construction in this answer might be better suited (function separated by comma instead of parenthesis).
terminal(x) returns an applicator that method-chains its return value into terminal for repeated invocation.
But we could instead generalize it.
Suppose you have a function F. F takes an argument, and stuffs it on a stack.
It then examines the stack. If the top of the stack, evaluated on some subset of the stack, would work for invocation, it does it, and pushes the result back onto the stack. In general, such invocation could return a tuple of results.
So:
F(3)(2)(add)(2)(subtract)(7)(3)(multiply)(power)
would evaluate to:
((3+2)-2)^(7*3)
Your terminal does this with 0 argument functions (the first argument) and with 1 argument functions (every argument after that), and only supports 1 return value per invocation.
Doing this with a lambda would be tricky, but what I described is doable in C++.
So one name for it would be stack-based programming.
As far as I know there is no "official" name, yet.
Suggestions:
Lambda chain
Lambda sausage
Curry sausage

Call lambda without binding it to an identifier

Browsing some internet board I encountered this little challenge:
"Implement a recursive anonymous function in your favorite language"
Obviously this is easy using a std::function/function pointer.
What I'm really interested in is if this is possible without binding the lambda to an identifier?
Something like (ignoring the obvious infinite recursion):
[](){ this(); }();
Of course, in C++, to call any function you have to bind it to an identifier somewhere, simply owing to syntax constraints. But, if you will accept parameters as being sufficiently unnamed, then it is possible to create a version of the y-combinator in C++ which recurses nicely without being "named".
Now, this is really ugly because I don't know how to do a typedef for a recursive lambda. So it just uses a lot of cast abuse. But, it works, and prints FLY!! until it segfaults due to stack overflow.
#include <iostream>
typedef void(*f0)();
typedef void(*f)(f0);
int main() {
[](f x) {
x((f0)x);
} ([](f0 x) {
std::cout<<"FLY!!\n";
((f)x)(x);
});
}
The two lambdas are unnamed in the sense that neither is explicitly assigned to name anywhere. The second lambda is the real workhorse, and it basically calls itself by using the first lambda to obtain a reference to itself in the form of the parameter.
Here's how you would use this to do some "useful" work:
#include <iostream>
typedef int param_t;
typedef int ret_t;
typedef void(*f0)();
typedef ret_t(*f)(f0, param_t);
int main() {
/* Compute factorial recursively */
std::cout << [](f x, param_t y) {
return x((f0)x, y);
} ([](f0 x, param_t y) {
if(y == 0)
return 1;
return y*((f)x)(x, y-1);
}, 10) << std::endl;
}
Are you allowed to cheat?
void f(){
[]{ f(); }();
}
It's recursive - indirectly, atleast.
Otherwise, no, there is no way to refer to the lambda itself without assigning it a name.
No identifier for functions/methods, Close enough or not !?
struct A
{
void operator()()
{
[&]()
{
(*this)();
}();
}
};
To call
A{}(); // Thanks MooningDuck
I seem to have come up with a solution of my own:
#include <iostream>
int main()
{
std::cout<<"Main\n";
[&](){
std::cout<<"Hello!\n";
(&main+13)();
}();
}
First call to cout is present just to show that it's not calling main.
I came up with the 13 offset by trial and error, if anyone could explain why it's this value it would be great.

Auto type inference with functor does not work [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
std::bind a bound function
void foo0(int val) { std::cout << "val " << val << "\n"; }
void foo1(int val, std::function<void (int)> ftor) { ftor(val); }
void foo2(int val, std::function<void (int)> ftor) { ftor(val); }
int main(int argc, char* argv[]) {
auto applyWithFoo0 ( std::bind(foo0, std::placeholders::_1) );
//std::function<void (int)> applyWithFoo0 ( std::bind(foo0, std::placeholders::_1) ); // use this instead to make compile
auto applyFoo1 ( std::bind(foo1, std::placeholders::_1, applyWithFoo0) );
foo2(123, applyFoo1);
}
The sample above does not compile giving multiple errors like: Error 1 error C2780: '_Ret std::tr1::_Callable_fun<_Ty,_Indirect>::_ApplyX(_Arg0 &&,_Arg1 &&,_Arg2 &&,_Arg3 &&,_Arg4 &&,_Arg5 &&,_Arg6 &&,_Arg7 &&,_Arg8 &&,_Arg9 &&) const' : expects 10 arguments - 2 provided.
Using the commented line with explicit type does compile. It seems that the type inferred by auto is not correct. What is the problem with auto in this case?
Platform: MSVC 10 SP 1, GCC 4.6.1
The issue is that std::bind treats "bind expression" (like your applyWithFoo0) differently from other types. Instead of calling foo1 with applyWithFoo0 as parameter it tries to invoke applyWithFoo0 and pass its return value to foo1. But applyWithFoo0 doesn't return anything that is convertible to std::function<void(int)>. The intention of handling "bind expressions" like this is to make them easily composable. In most cases you probably don't want bind expression to be passed as function parameters but only their results. If you explicitly wrap the bind expression into a function<> object, the function<> object will simply be passed to foo1 directly since it is not a "bind expression" and therefore not handled specially by std::bind.
Consider the following example:
#include <iostream>
#include <functional>
int twice(int x) { return x*2; }
int main()
{
using namespace std;
using namespace std::placeholders;
auto mul_by_2 = bind(twice,_1);
auto mul_by_4 = bind(twice,mul_by_2); // #2
auto mul_by_8 = bind(twice,mul_by_4); // #3
cout << mul_by_8(1) << endl;
}
This actually compiles and works because instead of passing a functor to twice like you might expect from the bind expressions #2 and #3, bind actually evaluates the passed bind expressions and uses its result as function parameter for twice. Here, it is intentional. But in your case, you tripped over this behaviour by accident because you actually want bind to pass the functor itself to the function instead of its evaluated value. Wrapping the functor into a function<> object is obviously a work-around for that.
In my opinion this design decision is a bit awkward because it introduces an irregularity people have to know about to be able to use bind correctly. Maybe, we'll get another more satisfying work around in the future like
auto applyFoo1 = bind( foo1, _1, noeval(applyWithFoo0) );
where noeval tells bind not to evaluate the expression but to pass it directoy to the function. But maybe the other way around -- explicitly telling bind to pass the result of a functor to the function -- would have been a better design:
auto mul_by_8 = bind( twice, eval(mul_by_4) );
But I guess, now it's too late for that ...
My guess is the parentheses around the std::bind make the parser think you're declaring functions named applyWithFoo0 and applyFoo1.
std::bind returns a functor the type of which auto should be able to detect.
Try this:
int main(int argc, char* argv[]) {
auto applyWithFoo0 = std::bind(foo0, std::placeholders::_1);
//std::function<void (int)> applyWithFoo0 std::bind(foo0, std::placeholders::_1) ); // use this instead to make compile
auto applyFoo1 = std::bind(foo1, std::placeholders::_1, applyWithFoo0);
foo2(123, applyFoo1);
}

How to use std::log as a functional?

I try to pass std::log as a functional argument, but it seems that there are overloaded implementations of std::log and the compiler failed to resolve it. Codes:
#include <cmath>
#include <iostream>
#include <vector>
#include <string>
#include <functional>
template <typename FOper>
double Eval(FOper fOper, double X)
{
return fOper(X);
}
int main(int argc, char* argv[])
{
std::function<double(double)> fPlus1 = std::bind(std::plus<double>(), 1.0, std::placeholders::_1);
std::cout<<Eval(fPlus1, 10.0)<<std::endl;
// how to write this fLog ?
//std::function<double(double)> fLog = std::log;
//std::function<double(double)> fLog = std::log<double>;
std::cout<<Eval(fLog, 10.0)<<std::endl;
return 0;
}
The complier prompts an error message if I uncomment either line of the definition of fLog:
error: conversion from '<unresolved overloaded function type>' to non-scalar type 'std::function<double(doubl
e)>' requested
The easiest way would be to simply cast it:
typedef double (*log_d)(double);
std::function<double(double)> fLog = static_cast<log_d>(std::log);
With the cast, you hand the compiler a context in which the overloaded function is used, and as such will get the correct function pointer out of it.
Like Xeo explained, it is possible to get it to work even when the function is overloaded using an explicit cast. However, since you're using std::function already (which is a C++11 feature), you might as well just use a lambda expression as initializer:
function<double(double)> fLog = [](double x){return std::log(x);};
This is preferable in C++11 because it avoids overloading issues. Also, it is more efficient than wrapping a function pointer because it saves one level of indirection and therefore allows the lambda's body to be inlined into the internal wrapper object's function call operator.
It should probably be stressed that the use of std::function in your example is unnecessary since Eval is already a function template and the type parameter FOper can exactly match the type of the function object without the need to wrap it inside std::function. So, if you don't need the type erasure you get by using std::function, you could just as well write
template <typename FOper>
double Eval(FOper fOper, double X)
{
return fOper(X);
}
int main()
{
auto flog = [](double x){return std::log(x);};
std::cout << Eval(flog, 10.0) << std::endl;
}
You do this:
typedef double (*logtype)(double);
std::function<double(double)> fLog = (logtype) std::log;
The cast will help compiler to select the correct overload.
You can also write this:
double (*fLog )(double) = std::log; //i.e don't use std::function
std::cout<<Eval(fLog, 10.0)<<std::endl;
The issue is that something like this on its own has no meaning:
std::bind( std::log, _1 ); // cannot resolve. bind what function? What will _1 be passed as?
log is not a template so you can't call std::log<double> in there.
You can make your own template though, that will resort to log:
template< typename T >
T logT( T t )
{
return std::log( t );
}
and now you can use logT in your code.
std::bind( logT<double>, _ 1 ) // should work.
You could of course make fLog a function pointer to logT if you want. With C++11 you can use auto etc. to not have to type out its type by hand.

how to combine 2 independent boost::bind() into one boost::function?

I have 2 functions f() and g(). I want to call them in order every time. Can I get a boost::function to do this?
E.g. something like:
boost::function functor = boost::bind( boost::bind(f), boost::bind(g) );
Extend this further, say it takes arguments, then what I need is a chain of responsibility. Each node does something with arguments, then followed by next node of chain.
How do I do that?
Update Thanks for Seth Carnegie's comments.
I think what I really want is how to construct a chain of responsibility into a single boost::function, each node of chain can be constructed by using boost::bind().
Have you considered using boost::signal ?
With boost::signal you can connect multiple function calls into one.
#include <boost/signal.hpp>
#include <iostream>
void f()
{
std::cout << " Hello" << std::flush;
}
void g()
{
std::cout << " World" << std::endl;
}
int main()
{
boost::signal<void ()> s;
s.connect(f);
s.connect(g);
s();
}
Why not something like this?
#include <functional>
template <typename FirstFunctor, typename SecondFunctor>
void chainFunctionImpl(FirstFunctor first, SecondFunctor second)
{
first();
second();
}
template <typename FirstFunctor, typename SecondFunctor>
std::function<void(void)> chainFunction(FirstFunctor first, SecondFunctor second)
{
return std::bind(chainFunctionImpl<FirstFunctor,SecondFunctor>,first,second);
}
Use should be relatively simple, just binding the functions in sequence, then calling the result. Theoretically any length of functions could be chained up.
Note that is theoretically possible to do this with passing an argument down the chain as well, but that level of template foo is way beyond me. http://ideone.com/Xvp5U is where I gave up.
There is a quite easy solution using boost::lambda with its comma operator. In my case I am using it for a modificator function which is defined as (B is an arbitrary class for e.g. and A is a class which should be altered but resides in B and should not go outside)
void B::modify( boost::function<void(A&)> func );
My intention is to pass only the modificator to the modify function which makes it more easy to gain control when it is modified (for e.g. for emitting signals).
Sometimes I want to apply 2 modifier:
void A::setInvalid();
void A::setX( int x );
Calling in 2 steps which is not the way (just as reference to show how we want to use the modify method):
instanceA->modify(
boost::bind( &A::setInvalid, _1 );
instanceA->modify(
boost::bind( &A::setX, _1, 4 );
Using boost::lambda this can be joined to a single function call and therefore only one function is created:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;
instanceA->modify(
( bind(&A::setInvalid, boost::lambda::_1)
, bind(&A::setX, boost::lambda::_1, 4) ) );
Related to your question this would look then:
using namespace boost::lambda;
boost::function<void()> func = ( bind(f), bind(g) )