180*_*ION 10 c++ bind y-combinator
我对使用定点组合器的实际例子很感兴趣(例如C++中的y-combinator.你有没有使用带有egg的固定点组合器或绑定真实的实时代码?
我在蛋中发现这个例子有点密集:
void egg_example()
{
using bll::_1;
using bll::_2;
int r =
fix2(
bll::ret<int>(
// \(f,a) -> a == 0 ? 1 : a * f(a-1)
bll::if_then_else_return( _2 == 0,
1,
_2 * lazy(_1)(_2 - 1)
)
)
) (5);
BOOST_CHECK(r == 5*4*3*2*1);
}
Run Code Online (Sandbox Code Playgroud)
你能解释一下这一切是怎么回事吗?
是否有一个很好的简单例子,或许使用bind可能比这个更少的依赖?
Ted*_*Ted 32
这是相同的代码转换为boost::bind通知y-combinator及其主要功能中的应用程序站点.我希望这有帮助.
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
// Y-combinator compatible factorial
int fact(boost::function<int(int)> f,int v)
{
if(v == 0)
return 1;
else
return v * f(v -1);
}
// Y-combinator for the int type
boost::function<int(int)>
y(boost::function<int(boost::function<int(int)>,int)> f)
{
return boost::bind(f,boost::bind(&y,f),_1);
}
int main(int argc,char** argv)
{
boost::function<int(int)> factorial = y(fact);
std::cout << factorial(5) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
#include <functional>
#include <iostream>
template <typename Lamba, typename Type>
auto y (std::function<Type(Lamba, Type)> f) -> std::function<Type(Type)>
{
return std::bind(f, std::bind(&y<Lamba, Type>, f), std::placeholders::_1);
}
int main(int argc,char** argv)
{
std::cout << y < std::function<int(int)>, int> ([](std::function<int(int)> f, int x) {
return x == 0 ? 1 : x * f(x - 1);
}) (5) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)