Functional Programming in C++: Why?
On and off I will read an article about functional programming as a supposedly ultra useful paradigm in programming. So naturally I would be interested in using this with C++. I have used some forms of functional programming in Python and it seems useful in some cases. However, I have not seen a real use for it in my day to day C++ code. Every article I have read usually shows how to write generic functions (which can be reused), but it is usually coupled with code that calls a function for each element of a container. This seems wasteful to call a function so many times when a decent loop can do the same thing. Yes, I get the idea of reducing errors by not using local variables as intrinsic to the style. Yet the performance hit would seem to be huge with lots and lots of function calls.
So is that the trade-off with functional programming in C++? Very generic code (high reuseability) vs massive amounts of function calls. Does the compiler just treat these calls like a jump for a lambda? Or is it actually stuffing things onto and off the stack for each call? If it is a paradigm shift, I am just not seeing the value of the paradigm.
Also, according to people who know, C++ now has most of the things required to do functional programming.
Ivan Čukić's book: Functional Programming in C++ has pretty good explanation about the rational behind.
These 2 videos on youtube helped a bit as well. That book looks very interesting.
So is that the trade-off with functional programming in C++? Very generic code (high reuseability) vs massive amounts of function calls. Does the compiler just treat these calls like a jump for a lambda?
Not really no. If you're using inline functors (e.g. templates or function objects that are inlined) the compiler's going to optimize the living daylights out of any function calls. In the end you're going to end up with no
calls in the assembly.
Lambdas are not functions. Ideologically they're objects, but in practice the compiler inlines every last piece of them, so their bodies end up directly in code, as if they never existed.
If it is a paradigm shift, I am just not seeing the value of the paradigm.
There's some value in some places. For example Eigen uses expression templates to lazy evaluate the matrix/vector operations it does. As usual it's a tool, which is transforming to a fad in recent times. Best advice: use it when it makes sense, don't when it doesn't.