0

I have some user-provided input strings that represent symbolic math expressions.

Example input:

a = 1
b = 2
c = a + 5
d = b + 2
e = c + d

Note that:

  1. a and b are assigned the user-provided value as an initial value but they will be constantly updated at runtime
  2. e depends on c and d, which in turn depend on a and b

Once a and b are updated, I need to re-evaluate the expressions for c, d and e. Note that I don't know how many variables the user will provide or what they will be called.

The best I could come up with is a class (or struct) that keeps track of the variable name chosen by the user (std::string) and of its current value (double). Then create a vector to handle all the user-provided variables together.

Something like (I am simplifying):

class UserVar
{
public:
  UserVar(const std::string &name, double value)
    : name(name), value(value) {}
  const std::string name;
  double value;
}

void main()
{
  std::vector<UserVar> user_vars;
  // Fill user_vars with UserVar(unique_name, init_value) provided by user in input file
  // ...

  while (condition)
  {
    // Update a and b
    // ...

    for (auto & var: user_vars)
      var.value = // parse and evaluate var.name every time
  }
}

Obviously this is not optimal (in particular I don't like re-parsing the expression at every loop). I also looked at closures, though they would need to be defined by the user one by one and that doesn't sound like a good idea.

Is there a "proper" way to do this?

It is not mandatory to have an input file, it just looked like the most straightforward way to provide a long list of expressions (possibly hundreds). It would totally possible to define some sort of interface and have the user define a custom function, if that simplifies the code (suggestions?).

Thanks!

giacomo-b
  • 394
  • 3
  • 13
  • 9
    You are asking how to write an interpreter for a small programming language. You should read a book about the subject. – n. m. could be an AI Feb 27 '21 at 19:46
  • Or embed some existing small programming language, like Lua. – rici Feb 27 '21 at 22:07
  • @n.'pronouns'm. wouldn't an interpreter just help during the parsing phase? How would it come to rescue at every iteration when I need to update the variables? Also, is there a specific book you would suggest? Thanks! – giacomo-b Feb 28 '21 at 08:43
  • 1
    An interpreter both parses and evaluates the program. It's a very broad notion. I recommend [the Dragon Book](https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools). – n. m. could be an AI Feb 28 '21 at 08:53
  • @n.'pronouns'm. thank you! – giacomo-b Feb 28 '21 at 19:54
  • here very simple parser: [Sign of a symbolic algebraic expression](https://stackoverflow.com/a/20919547/2521214) I use (for function plotting, numerical integration and algebraic math in my apps) – Spektre Mar 01 '21 at 08:12

0 Answers0