如何在 C++ 中进行柯里化? [英] How can currying be done in C++?

查看:38
本文介绍了如何在 C++ 中进行柯里化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是咖喱?

如何在 C++ 中实现柯里化?

请解释 STL 容器中的绑定器?

解决方案

简而言之,柯里化需要一个函数 f(x, y) 并给定一个固定的 Y,给出一个新函数 g(x) where

g(x) == f(x, Y)

这个新函数可以在只提供一个参数的情况下被调用,并将调用传递给带有固定 Y 参数的原始 f 函数.>

STL 中的绑定器允许您为 C++ 函数执行此操作.例如:

#include #include #include <向量>使用命名空间标准;//声明一个二元函数对象类加法器:public binary_function{上市:int operator()(int x, int y) const{返回 x + y;}};int main(){//初始化一些样本数据向量一、乙;a.push_back(1);a.push_back(2);a.push_back(3);//这里我们声明了一个函数对象 f 并尝试一下加法器 f;cout<<"f(2, 3) = " <<f(2, 3)<<结束;//transform() 需要一个带一个参数的函数,所以我们使用//bind2nd 创建一个基于 f 的新函数,它需要一个//参数并将其加 5变换(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));//输出 b 看看我们得到了什么cout<<"b = [" <<结束;for (vector::iterator i = b.begin(); i != b.end(); ++i) {cout<<" " <<*我<<结束;}cout<<"]" <<结束;返回0;}

What is currying?

How can currying be done in C++?

Please Explain binders in STL container?

解决方案

In short, currying takes a function f(x, y) and given a fixed Y, gives a new function g(x) where

g(x) == f(x, Y)

This new function may be called in situations where only one argument is supplied, and passes the call on to the original f function with the fixed Y argument.

The binders in the STL allow you to do this for C++ functions. For example:

#include <functional>
#include <iostream>
#include <vector>

using namespace std;

// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
    int operator()(int x, int y) const
    {
        return x + y;
    }
};

int main()
{
    // initialise some sample data
    vector<int> a, b;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    // here we declare a function object f and try it out
    adder f;
    cout << "f(2, 3) = " << f(2, 3) << endl;

    // transform() expects a function with one argument, so we use
    // bind2nd to make a new function based on f, that takes one
    // argument and adds 5 to it
    transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));

    // output b to see what we got
    cout << "b = [" << endl;
    for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
        cout << "  " << *i << endl;
    }
    cout << "]" << endl;

    return 0;
}

这篇关于如何在 C++ 中进行柯里化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆