Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can currying be used with lambda functions?

This piece of code fails to compile and I don't know if it is because it can not be done, lambdas do not inherit from binary_function, or it is just that I'm getting the syntax wrong

#include <functional>

int main(int argc, const char *argv[])
{
   auto lambda = [](int x, int y) -> int { return x + y; };
   auto sumFive = std::bind1st(lambda, 5); 

   return 0;
}
like image 577
tonicebrian Avatar asked Aug 24 '11 14:08

tonicebrian


People also ask

What is currying in Lambda?

Currying simply means breaking up a Lambda expression so that it accepts up to one input and has up to one output. Each input and expression calculates one part of the solution, and the output from that Lambda expression is an input to the next Lambda expression in the chain.

When should we use currying?

Currying is helpful when you have to frequently call a function with a fixed argument. Considering, for example, the following function: If we want to define the function error , warn , and info , for every type, we have two options. Currying provides a shorter, concise, and more readable solution.

Does Python support currying?

Python does not have an explicit syntax for Currying functions; but it does provide infrastructure that allows Curried functions to be created.

How would you implement currying for any functions?

In other terms, currying is when a function — instead of taking all arguments at one time — takes the first one and returns a new function, which takes the second one and returns a new function, which takes the third one, etc. until all arguments are completed.


1 Answers

Use:

auto sumFive = std::bind(lambda, 5, std::placeholders::_1);

Please forget entirely about bind1st and binary_function, etc. Those were crutches in the old C++ because of the lack of lambdas and variadic templates. In C++11, use std::function and std::bind.

like image 165
Kerrek SB Avatar answered Sep 20 '22 15:09

Kerrek SB