Pass lambda expression from the command line

3

I created a program to calculate the definite integral of a function, but I want to be able to execute it by the terminal.

#include <iostream>
#include <functional>
#include <cmath>

#define PI acos(-1)

using namespace std;

// Função que calcula a integral de uma função matemática (func) no intervalo
// [inf, sup] com Δx = (inf - sup) / n e inf <= sup
inline long double integral (const function<long double (const long double&)> &func, const long double &inf, const long double &sup, const long double &n) {
  if (inf > sup) return 0;
  if (n <= 0) return 0;

  register long double &&area = 0;
  register long double &&delta = (sup - inf) / n;

  for (register long double i = inf; i <= sup; i += delta) {
    area += delta * func(i);
  }
  return area;
}

int main () {
  const function<long double (const long double&)> &&f1 = [](const long double &x)-> long double {return pow(sin(x), 3) * cos(x);};
  const long double &vf1 = integral(f1, 0, PI / 2, 10000000.0);

  const function<long double (const long double&)> &&f2 = [](const long double &x)-> long double {return sin(x);};
  const long double &vf2 = integral(f2, 0, 2 * PI, 10000000.0);

  const function<long double (const long double&)> &&f3 = [](const long double &x)-> long double {return x * x;};
  const long double &vf3 = integral(f3, 0, 1, 10000000.0);

  const function<long double (const long double&)> &&f4 = [](const long double &x)-> long double {return sqrt(1 - x * x);};
  const long double &vf4 = integral(f4, 0, 1, 10000000.0);

  cout << "Area: " << vf1 << " u.a" << endl;
  cout << "Area: " << vf2 << " u.a" << endl;
  cout << "Area: " << vf3 << " u.a" << endl;
  cout << "Area: " << vf4 << " u.a" << endl;
  return 0;
}

I wanted to be able to do something like this on the command line:

integral "x*x" 0 1 100000

Any suggestions / tips?

    
asked by anonymous 24.07.2016 / 03:04

1 answer

4

Lambda is something inside the code (essentially a pointer to a function), not through the command line (not a magic thing that transforms into executable code). >

The only way to get something close to what you want is to create a parser (even if simplified to meet only some code types) from the content passed to the main() parameter and select the < in> lambda that you want according to what you find. It's a very complex thing to do for something that seems to be just a simple exercise.

What could make it simpler is to have a parameter that would receive a number that would serve an index to a predefined lambdas vector with some operations.

register is innocuous in C ++. Probably should not use inline . I think there are other unnecessary complications in this code.

    
24.07.2016 / 03:20