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:
a
andb
are assigned the user-provided value as an initial value but they will be constantly updated at runtimee
depends onc
andd
, which in turn depend ona
andb
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!