Y-combinator是一种来自事物"功能"方面的计算机科学概念.大多数程序员对组合器一无所知,如果他们甚至听说过它们的话.
theory computer-science functional-programming combinators definition
只是想整理一个程序,并想知道是否有人可以在同一行上多次调用一个队列上的成员函数给我一些语法糖.
例如,更改:
queue<int> q;
q.push(0);
q.push(1);
Run Code Online (Sandbox Code Playgroud)
类似于:
q.(push(0), push(1));
//or
q.push(0).push(1);
Run Code Online (Sandbox Code Playgroud)
我知道它看起来有点荒谬,并不实用.但是,如果我想缩短这样的一小部分代码,是否可以选择这样做?从我到目前为止所读到的内容来看,只有在函数具有非void返回值时才能链接方法.
当然,这是一个选项:
q.push(0); q.push(1);
Run Code Online (Sandbox Code Playgroud)
但我试图避免在q那里两次.再次......语法糖:)
这里的目标不是初始化,而是压缩对象/容器在代码块中生成的次数.我引用队列的原因是因为它是动态的.
c++ member-functions syntactic-sugar function-calls method-chaining
考虑一个正常的递归函数:
#include <iostream>
#include <functional>
void f(unsigned long long int x) {
std::cout << x << "\n";
if(x < 1e9)
f(x+1);
}
int main() {
f(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这终止于43033.
现在考虑一个递归的lambda:
#include <iostream>
#include <functional>
int main() {
std::function<void(int)> g = [&g](unsigned long long int x) {
std::cout << x << "\n";
if(x < 1e9)
g(x+1);
};
g(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这终止于低得多的堆叠深度11736.
为什么lambda的最大堆栈深度较低?
(用g++ (GCC) 5.4.0,编译-std=c++14 -Wall)
还要注意,使用-O3优化进行编译可以实现几乎无限的递归深度,但lambda仍然以 …
我想使用lambdas和重载创建函数(例如)访问"递归" .std::variantboost::hana::overload
假设我有一个变量类型my_variant,可以存储一个a int,a float或a vector<my_variant>:
struct my_variant_wrapper;
using my_variant =
std::variant<int, float, std::vector<my_variant_wrapper>>;
struct my_variant_wrapper
{
my_variant _v;
};
Run Code Online (Sandbox Code Playgroud)
(我正在使用包装my_variant_wrapper类来递归地定义变体类型.)
我想以递归方式访问变体,根据存储的类型打印不同的东西.这是一个使用基于访问者的工作示例struct:
struct struct_visitor
{
void operator()(int x) const { std::cout << x << "i\n"; }
void operator()(float x) const { std::cout << x << "f\n"; }
void operator()(const std::vector<my_variant_wrapper>& x) const
{
for(const auto& y : x) std::visit(*this, y._v);
}
};
Run Code Online (Sandbox Code Playgroud)
std::visit使用上述访问者调用打印所需的输出: …
c++ ×3
lambda ×2
boost-hana ×1
c++17 ×1
combinators ×1
definition ×1
function ×1
recursion ×1
theory ×1
variant ×1