views:

159

answers:

3

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

A: 

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

chakrit
Then why don't go for Spirit? Results in less dependencies on external tools (I consider Spirit less external than yacc and friends)
Anonymous
In the context of spirit vs. yacc, then I would certainly go for boost. However, I also see that matheval is lightweight as well as easier to use for a less complicated grammar. Thanks
A: 

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?

joshperry
well, it could be a bit tricky as I have to use many different operators (- + * /)- formula can go use 30 constants, some might repeated.
Both libraries fulfill my requirements, as far as I can tell ...the question is extensibility and complexity with using one over the other...
A: 

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.

Benoît