lundi 22 janvier 2018

functional approach to cpp

I am trying to build some nested functions like so (reduced example):

// the actual functions come from particle physics and are extremely ugly 
double f(double x){
  return 2*x+1;
}
//in reality a numerical derivative term
double F(const std::function<double(double)>& f, double x){
  return f(x) - f(x+1);
}
// in reality another higher order numerical derivative
double G(const std::function<double(double)>& f, double x){
  return f(x) + f(x+1);
}
// in reality a function where the index is supposed to control the degree of derivatives of the function
double H(const std::function<double(double)>& f, double x, int switch){
  if(0 == switch){ 
    return G(f(x)); 
  } else {
    return F(f(x));
  }
}

this is the goal (2d for demonstration):

double sum=0;
for(int i=0; i<1;++i){
  for(int j=0; j<1;++j){
    sum += H(H(f,i),j); 
  }
}

So two things:

  1. I want to use a function H to switch between F and G (my actual problem has 3 cases).
  2. I would like to find a way/concept of calling H(H(...)...) the problem with that is the type of the function f which is the first argument of H, when I pass it a second time the type is no longer double(double) but double(std::function<double(double)>,double(double),double) or so...

Or in other terms: https://i.stack.imgur.com/XkbmJ.gif (cannot post images, not enough rep)

Aucun commentaire:

Enregistrer un commentaire