3
votes

I will first describe the problem and then what I currently look at, in terms of libraries.

In my application, we have a set of variables that are always available. For example: TOTAL_ITEMS, PRICE, CONTRACTS, ETC (we have around 15 of them). A clients of the application would like to have certain calculations performed and displayed, using those variables. Up until now, I have been constantly adding those calculations to the app. It's pain in the butt, and I would like to make it more generic by way of creating a template, where the user can specify a set of formulas that the application will parse and calculate.

Here is one case:

total_cost = CONTRACTS*PRICE*TOTAL_ITEMS

So, want to do something like that for the user to define in the template file:

total_cost = CONTRACTS*PRICE*TOTAL_ITEMS and some meta-date, like screen to display it on. Hence they will be specifying the formula with a screen. And the file will contain many formulas of this nature.

Right now, I am looking at two libraies: Spirit and matheval

Would anyone make recommendations what's better for this task, as well as references, examples, links?

Please let me know if the question is unclear, and I will try to further clarify it .

Thanks,

Sasha

3
It looks like matheval was written in Euphoria... is that a problem for your use-case? - joshperry
What is the problem with that? - Sasha
I guess the main problem is that you need Euphoria ! :-) - Benoît
Isn't just a cpp binary? it works for us, for other apps, on AS3.. - Sasha
I guess Euphoria can be compiled to C and exported as C functions in a DLL so that is probably what you are using. - joshperry

3 Answers

0
votes

If you have a fixed number of variables it may be a bit overkill to invoke a parser. Though Spirit is cool and I've been wanting to use it in a project.

I would probably just tokenize the string, make a map of your variables keyed by name (assuming all your variables are ints):

map<const char*,int*> vars;
vars["CONTRACTS"] = &contracts;
...

Then use a simple postfix calculator function to do the actual math.

Edit:

Looking at MathEval, it seems to do exactly what you want; set variables and evaluate mathematical functions using those variables. I'm not sure why you would want to create a solution at the level of a syntax parser. Do you have any requirements that MathEval does not fulfill?

0
votes

Looks like it shouldn't be too hard to generate a simple parser using yacc and bison and integrate it into your code.

0
votes

I don't know about matheval, but boost::spirit can do that for you pretty efficiently : see there.

If you're into template metaprogramming, you may want to have a look into Boost::Proto, but it will take some time to get started using it.