C# 语言实现 YCombinator(Y组合子)及多个简化代码分解_liulilittle的博客-CSDN博客
具体实现过程,可以参考上述提供博文,本人适用 C#语言实现的Y组合子及分解过程:
以下:
C/C++ 11 实现 YCombinator(Y组合子):源代码及测试代码。
#include <iostream>
#include <functional>
template <typename T, typename TResult>
class RecursiveFunction
{
public:
using FunctionType = std::function<TResult(T)>;
using RecursiveType = std::function<FunctionType(RecursiveFunction)>;
public:
RecursiveFunction(const RecursiveType& f)
: m_f(f)
{
}
public:
TResult operator ()(T arg) const
{
return m_f(*this)(arg);
}
private:
RecursiveType m_f;
};
template <typename T, typename TResult>
class YCombinator final
{
public:
// Y = λf.(λx.f(x x)) (λx.f(x x))
// Y = f => (λx.f(x x)) (λx.f(x x))
// Y = f => (x => f(x(x)))(x => f(x(x)))
// Y = (x => arg => f(x(x))(arg))(x => arg => f(x(x))(arg))
static typename RecursiveFunction<T, TResult>::FunctionType Y(typename RecursiveFunction<T, TResult>::RecursiveType&& f)
{
auto g = [](auto x) -> typename RecursiveFunction<T, TResult>::FunctionType
{
return [x](T arg) -> TResult
{
return x(x)(arg);
};
};
return g([f](auto x) -> typename RecursiveFunction<T, TResult>::FunctionType
{
return f(RecursiveFunction<T, TResult>{x});
});
}
};
int main(int argc, const char* argv[])
{
auto factorial = ppp::expressions::YCombinator<int, int>::Y(
[](auto f)
{
return [f](int n) -> int { return n <= 1 ? 1 : n * f(n - 1); };
});
std::cout << factorial(5) << std::endl; // 输出:120
}