Re: math parser ?
Daniel Pitts wrote:
Eric Sosman wrote:
mark wrote:
Does anyone knows any api or example for parsing and calculating math
expressions like this ?
(x+y)/(y+z)
I've written such a thing, but it's a bit long for a
Usenet post (checks: 1148 lines). It may also be overly
elaborate to the point of being baroque, since I did it as
a learning exercise and threw in all sorts of bells and
whistles. The usage is like
Expression expr = Expression.compile(
"length * width * sin(angle * PI / 180)",
new String[] { "length", "width", "angle" } );
double v1 = expr.value( new double[] { 3, 4, 45 } );
double v2 = expr.value( new double[] { 12, 13, 22.5 } );
...
Drop me a line if you'd like a copy by E-mail.
I don't get why so many people write there own. There are plenty of
easy and free libraries, depending on your need.
As I said, I wrote it at least in part as an exercise. If there's
a way to get the benefits of exercise without actually doing it oneself,
my waistline and I will thank you to tell us about it. :-)
OGNL <http://www.opensymphony.com/ognl/> is a great one, I use all the
time as an embedded language. There are plenty of others as well.
Had I been looking for an expression evaluator, I think the chance
of recognizing OGNL as such would have been slim. The page says
"OGNL stands for Object-Graph Navigation Language; it is an
expression language for getting and setting properties of Java
objects. You use the same expression for both getting and
setting the value of a property."
True, the word "expression" does in fact appear. But a language for
navigating object graphs and getting and setting properties does not,
on the face of it, sound like an evaluator for "(x+y)/(y+z)".
Apparently, OGNL can in fact evaluate such expressions, and that's
fine. But doesn't it seem like overkill for simple arithmetic? I'm
sure it's just lovely to be able to write "pseudo-lambda expressions"
and to manage "pseudo-properties for Collections" and to "project across
Collections" and so on (all these are section titles from the doc), but
does "(x+y)/(y+z)" require all that power?
My 1148 lines (about 750 if you strip the comments) fit in one count
them one self-contained .java source file. I described it as "elaborate
to the point of being baroque," but had I known of OGNL I would instead
have called it a lightweight marvel of bare-bones simplicity. OGNL may
be beautifully suited to its application area, but for this task... The
saying about cannon and canaries comes to mind.
--
Eric.Sosman@sun.com