[英]Functional programming in C++. Implementing f(a)(b)(c)
我已经开始使用C ++进行函数式编程的基础知识。 我试图使函数f(a)(b)(c)
返回a + b + c
。 我成功实现了函数f(a)(b)
,返回a + b。 这是它的代码:
std::function<double(double)> plus2(double a){
return[a](double b){return a + b; };
}
我只是无法弄清楚如何实现函数f(a)(b)(c)
,正如我之前所说,它应返回a + b + c
。
你可以通过让函数f
返回一个仿函数来实现它,即一个实现operator()
的对象。 这是一种方法:
struct sum
{
double val;
sum(double a) : val(a) {}
sum operator()(double a) { return val + a; }
operator double() const { return val; }
};
sum f(double a)
{
return a;
}
int main()
{
std::cout << f(1)(2)(3)(4) << std::endl;
}
您甚至可以编写一个模板化版本,让编译器推断出类型。 在这里试试吧。
template <class T>
struct sum
{
T val;
sum(T a) : val(a) {}
template <class T2>
auto operator()(T2 a) -> sum<decltype(val + a)> { return val + a; }
operator T() const { return val; }
};
template <class T>
sum<T> f(T a)
{
return a;
}
在这个例子中, T
将最终解决为double
:
std::cout << f(1)(2.5)(3.1f)(4) << std::endl;
只需使用2个元素解决方案并将其展开,然后用另一个lambda包装即可。
因为你想返回一个得到double
的lambda并返回一个double
s'加法lambda,你需要做的就是用另一个函数包装你当前的返回类型,并在你当前的一个中添加一个嵌套的lambda(一个返回的lambda)一个lambda):
std::function<std::function<double(double)>(double)> plus3 (double a){
return [a] (double b) {
return [a, b] (double c) {
return a + b + c;
};
};
}
正如@Ðan指出的那样,你可以跳过std::function<std::function<double(double)>(double)>
并与auto
相处:
auto plus3 (double a){ return [a] (double b) { return [a, b] (double c) { return a + b + c; }; }; }
您可以使用更深层次的嵌套lambda为每个元素扩展此结构。 演示4个元素:
auto plus4 (double a){ return [a] (double b) { return [a, b] (double c) { return [a, b, c] (double d) { return a + b + c + d; }; }; }; }
这是一个稍微不同的方法,它从operator()
返回对*this
的引用,因此您没有任何副本浮动。 这是一个非常简单的仿函数实现,它以递归方式存储状态和左折叠:
#include <iostream>
template<typename T>
class Sum
{
T x_{};
public:
Sum& operator()(T x)
{
x_ += x;
return *this;
}
operator T() const
{
return x_;
}
};
int main()
{
Sum<int> s;
std::cout << s(1)(2)(3);
}
这不是f(a)(b)(c)
,而是curry(f)(a)(b)(c)
。 我们将f
包装起来,使每个附加参数返回另一个curry
或者实际上热切地调用该函数。 这是C ++ 17,但可以在C ++ 11中实现,并带来一些额外的工作。
请注意,这是一个用于调整函数的解决方案 - 这是我从问题中得到的印象 - 而不是折叠二元函数的解决方案。
template <class F>
auto curry(F f) {
return [f](auto... args) -> decltype(auto) {
if constexpr(std::is_invocable<F&, decltype(args)...>{}) {
return std::invoke(f, args...);
}
else {
return curry([=](auto... new_args)
-> decltype(std::invoke(f, args..., new_args...))
{
return std::invoke(f, args..., new_args...);
});
}
};
}
为简洁起见,我跳过了转发参考。 示例用法是:
int add(int a, int b, int c) { return a+b+c; }
curry(add)(1,2,2); // 5
curry(add)(1)(2)(2); // also 5
curry(add)(1, 2)(2); // still the 5th
curry(add)()()(1,2,2); // FIVE
auto f = curry(add)(1,2);
f(2); // i plead the 5th
我能想到的最简单的方法是用plus2()
来定义plus3()
plus2()
。
std::function<double(double)> plus2(double a){
return[a](double b){return a + b; };
}
auto plus3(double a) {
return [a](double b){ return plus2(a + b); };
}
这将前两个参数列表组合成一个arglist,用于调用plus2()
。 这样做可以让我们以最少的重复次数重用我们已有的代码,并且可以在将来轻松扩展; plusN()
只需返回一个调用plusN-1()
的lambda, plusN-1()
将调用传递给前一个函数,直到达到plus2()
。 它可以像这样使用:
int main() {
std::cout << plus2(1)(2) << ' '
<< plus3(1)(2)(3) << '\n';
}
// Output: 3 6
考虑到我们只是在线调用,我们可以很容易地将其转换为函数模板,从而无需为其他参数创建版本。
template<int N>
auto plus(double a);
template<int N>
auto plus(double a) {
return [a](double b){ return plus<N - 1>(a + b); };
}
template<>
auto plus<1>(double a) {
return a;
}
int main() {
std::cout << plus<2>(1)(2) << ' '
<< plus<3>(1)(2)(3) << ' '
<< plus<4>(1)(2)(3)(4) << ' '
<< plus<5>(1)(2)(3)(4)(5) << '\n';
}
// Output: 3 6 10 15
在这里看到两个。
我要去玩了。
你想做一个curried折叠添加。 我们可以解决这个问题,或者我们可以解决一类包含这个问题的问题。
所以,首先,补充:
auto add = [](auto lhs, auto rhs){ return std::move(lhs)+std::move(rhs); };
这很好地表达了添加的概念。
现在,折叠:
template<class F, class T>
struct folder_t {
F f;
T t;
folder_t( F fin, T tin ):
f(std::move(fin)),
t(std::move(tin))
{}
template<class Lhs, class Rhs>
folder_t( F fin, Lhs&&lhs, Rhs&&rhs):
f(std::move(fin)),
t(
f(std::forward<Lhs>(lhs), std::forward<Rhs>(rhs))
)
{}
template<class U>
folder_t<F, std::result_of_t<F&(T, U)>> operator()( U&& u )&&{
return {std::move(f), std::move(t), std::forward<U>(u)};
}
template<class U>
folder_t<F, std::result_of_t<F&(T const&, U)>> operator()( U&& u )const&{
return {f, t, std::forward<U>(u)};
}
operator T()&&{
return std::move(t);
}
operator T() const&{
return t;
}
};
它需要种子值和T,然后允许链接。
template<class F, class T>
folder_t<F, T> folder( F fin, T tin ) {
return {std::move(fin), std::move(tin)};
}
现在我们连接它们。
auto adder = folder(add, 0);
std::cout << adder(2)(3)(4) << "\n";
我们也可以使用folder
进行其他操作:
auto append = [](auto vec, auto element){
vec.push_back(std::move(element));
return vec;
};
使用:
auto appender = folder(append, std::vector<int>{});
for (int x : appender(1)(2)(3).get())
std::cout << x << "\n";
实例 。
我们必须在这里调用.get()
,因为for(:)
循环不理解我们文件夹的operator T()
。 我们可以通过一些工作来解决这个问题,但是.get()
更容易。
如果您愿意使用库,那么在Boost的Hana中这很容易:
double plus4_impl(double a, double b, double c, double d) {
return a + b + c + d;
}
constexpr auto plus4 = boost::hana::curry<4>(plus4_impl);
然后使用它就像你想要的那样:
int main() {
std::cout << plus4(1)(1.0)(3)(4.3f) << '\n';
std::cout << plus4(1, 1.0)(3)(4.3f) << '\n'; // you can also do up to 4 args at a time
}
所有这些答案看起来都非常复杂。
auto f = [] (double a) {
return [=] (double b) {
return [=] (double c) {
return a + b + c;
};
};
};
完全符合你的要求,它可以在C ++ 11中运行,与许多或许多其他答案不同。
请注意,它不使用std::function
会导致性能下降,实际上,在很多情况下它可能会被内联。
这是一个状态模式单例启发方法,使用operator()
来改变状态。
编辑:为初始化交换了不必要的分配。
#include<iostream>
class adder{
private:
adder(double a)val(a){}
double val = 0.0;
static adder* mInstance;
public:
adder operator()(double a){
val += a;
return *this;}
static adder add(double a){
if(mInstance) delete mInstance;
mInstance = new adder(a);
return *mInstance;}
double get(){return val;}
};
adder* adder::mInstance = 0;
int main(){
adder a = adder::add(1.0)(2.0)(1.0);
std::cout<<a.get()<<std::endl;
std::cout<<adder::add(1.0)(2.0)(3.0).get()<<std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.