I have been getting into the basics of functional programming with C++. I am trying to make a function f(a)(b)(c)
that will return a + b + c
. I successfully implemented the function f(a)(b)
which returns a + b. Here is the code for it:
std::function<double(double)> plus2(double a){ return[a](double b){return a + b; }; }
I just cannot figure out how to implement the function f(a)(b)(c)
which as I previously stated should return a + b + c
.
Obviously, C is a procedural language and doesn't really support functional programming natively.
Introduction. Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”.
Functional programming languages are specially designed to handle symbolic computation and list processing applications. Functional programming is based on mathematical functions. Some of the popular functional programming languages include: Lisp, Python, Erlang, Haskell, Clojure, etc.
You can do it by having your function f
return a functor, i.e., an object that implements operator()
. Here is one way to do it:
struct sum { double val; sum(double a) : val(a) {} sum operator()(double a) { return val + a; } operator double() const { return val; } }; sum f(double a) { return a; }
Link
int main() { std::cout << f(1)(2)(3)(4) << std::endl; }
You can even write a templated version that will let the compiler deduce the type. Try it here.
template <class T> struct sum { T val; sum(T a) : val(a) {} template <class T2> auto operator()(T2 a) -> sum<decltype(val + a)> { return val + a; } operator T() const { return val; } }; template <class T> sum<T> f(T a) { return a; }
In this example, T
will ultimately resolve to double
:
std::cout << f(1)(2.5)(3.1f)(4) << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With