在C ++中的定点组合器 [英] Fixed point combinators in C++
本文介绍了在C ++中的定点组合器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对使用固定点组合器的实际示例感兴趣(例如 y-combinator < a> in C ++。你曾经使用过一个固定点组合器 egg 或绑定真实的实时代码?
I'm interested in actual examples of using fixed point combinators (such as the y-combinator in C++. Have you ever used a fixed point combinator with egg or bind in real live code?
我发现这个例子在egg有点密集:
I found this example in egg a little dense:
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);
}
你能解释一下这一切是如何工作的吗?
Can you explain how this all works?
有一个很好的简单例子可能使用bind,可能比这个更少的依赖性?
Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?
推荐答案
是相同的代码转换为 boost :: bind
注意y组合器及其应用程序网站在main函数。我希望这有助于。
Here is the same code converted into boost::bind
notice the y-combinator and its application site in the main function. I hope this helps.
#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;
}
这篇关于在C ++中的定点组合器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文