Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional programming in C++. Implementing f(a)(b)(c)

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.

like image 598
Gigaxel Avatar asked May 04 '17 12:05

Gigaxel


People also ask

Can functional programming be done in C?

Obviously, C is a procedural language and doesn't really support functional programming natively.

What is functional programming in C?

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”.

Can you give an example of functional programming?

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.


1 Answers

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; } 

Example

Link

int main() {     std::cout << f(1)(2)(3)(4) << std::endl; } 

Template version

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; } 

Example

In this example, T will ultimately resolve to double:

std::cout << f(1)(2.5)(3.1f)(4) << std::endl; 
like image 188
Jonas Avatar answered Sep 22 '22 11:09

Jonas