Partial application with a C++ lambda?

前端 未结 4 1779
粉色の甜心
粉色の甜心 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:48

    Your curry function is just a scaled down inefficient subcase of std::bind (std::bind1st and bind2nd should not be used anymore now that we have std::result_of)

    Your two lines read in fact

    auto f5 = std::bind(f, 5, _1);
    auto g2 = std::bind(std::multiplies(), 2, _1);
    

    after having used namespace std::placeholders. This carefully avoids the boxing into std::function and allows the compiler to inline more easily the result at the call site.

    For functions of two arguments, hacking something like

    auto bind1st(F&& f, T&& t) 
        -> decltype(std::bind(std::forward(f), std::forward(t), _1))
    {
        return std::bind(std::forward(f), std::forward(t), _1)
    }
    

    may work, but it is difficult to generalize to the variadic case (for which you'd end up rewriting a lot of the logic in std::bind).

    Also currying is not partial application. Currying has "signature"

    ((a, b) -> c) -> (a -> b -> c)
    

    ie. it is the action to transform a function taking two arguments into a function returning a function. It has an inverse uncurry performing the reverse operation (for mathematicians: curry and uncurry are isomorphisms, and define an adjunction). This inverse is very cumbersome to write in C++ (hint: use std::result_of).

提交回复
热议问题