在C ++中实现(类型化)K组合器 [英] Implementing the (typed) K combinator in C++
问题描述
我想从C ++中的 SK组合演算中实现K组合器。 K组合器是一个高阶函数,基本上需要一些值 x
,并返回依次取值 y
,并返回 x
从它。换句话说,
K(x)(y)== x
或分步:
intermediate = K(x)
intermediate(y)== x
c $ c> K(x)作为一个内在的东西,独立于 y
是必不可少的。此外,当简单地创建 K(x)
而不调用它时,不需要指定 y
的类型 y
。一旦 K(x)(y)
在代码中的某处被计算, y
/ p>
我试图修复我写的尝试实现K组合器的代码:
#include< iostream>
template< class A>
template< class B>
auto K = [](A x){
return [=](B y){
return x;
};
};
int main()
{
std :: cout< Hello world!\\\
;
auto Kx = K< int>(3);
auto Kxy = Kx< float>(4.5);
std :: cout<< Kxy < std :: endl;
}
输出错误:模板中的外部模板参数列表专业化或外联模板定义
。我已经尝试调整模板参数,并移动它们无法使用。有人知道如何解决这个错误吗?
Lambdas不能是模板。您可以这样做:
#include< iostream>
auto K = [](auto x){
return [=](auto y){
return x;
};
};
int main()
{
std :: cout< Hello world!\\\
;
auto Kx = K(3);
auto Kxy = Kx(4.5);
std :: cout<< Kxy < std :: endl;
}
这些被称为通用lambdas(存在自C ++ 14)基本上你想要什么。 运算符()
是每个 auto
参数的模板。
I am trying to implement the K combinator from the SK combinator calculus in C++. The K combinator is a higher-order function that basically takes some value x
, and returns something which in turn takes a value y
and returns x
from it. In other words,
K(x)(y) == x
or step-by-step:
intermediate = K(x)
intermediate(y) == x
The ability to treat K(x)
as a thing-in-itself, independent of y
, is essential. Furthermore, it should not be necessary to specify the type of y
when simply creating K(x)
without calling it on y
. The type of y
can be specified once K(x)(y)
is being evaluated somewhere in the code.
I am trying to fix the code I wrote which attempts to implement the K combinator:
#include <iostream>
template<class A>
template<class B>
auto K = [](A x) {
return [=](B y) {
return x;
};
};
int main()
{
std::cout << "Hello world!\n";
auto Kx = K<int>(3);
auto Kxy = Kx<float>(4.5);
std::cout << Kxy << std::endl;
}
It outputs error: extraneous template parameter list in template specialization or out-of-line template definition
. I have tried adjusting the template parameters and moving them around to no avail. Does anyone know how I could fix this error?
Lambdas cannot be templates. You can do this though:
#include <iostream>
auto K = [](auto x) {
return [=](auto y) {
return x;
};
};
int main()
{
std::cout << "Hello world!\n";
auto Kx = K(3);
auto Kxy = Kx(4.5);
std::cout << Kxy << std::endl;
}
These are called generic lambdas (exist since C++14), and are basically what you want. Their operator()
is template for each auto
parameter.
这篇关于在C ++中实现(类型化)K组合器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!