Partial application with a C++ lambda?

前端 未结 4 1784
粉色の甜心
粉色の甜心 2021-02-04 05:21

EDIT: I use curry below, but have been informed this is instead partial application.

I\'ve been trying to figure out how one would write a curry function in C++, and i a

4条回答
  •  故里飘歌
    2021-02-04 05:27

    With some C++14 features, partial application that works on lambda's can be implemented in a pretty concise way.

    template
    auto partial( _function foo, _val v )
    {
      return
        [foo, v](auto... rest)
        {
          return foo(v, rest...);
        };
    }
    
    template< typename _function, typename _val1, typename... _valrest >
    auto partial( _function foo, _val1 val, _valrest... valr )
    {
      return
        [foo,val,valr...](auto... frest)
        {
          return partial(partial(foo, val), valr...)(frest...);
        };
    }
    
    // partial application on lambda
    int p1 = partial([](int i, int j){ return i-j; }, 6)(2);
    int p2 = partial([](int i, int j){ return i-j; }, 6, 2)();
    

提交回复
热议问题