开发者

Parsing math rules (with some perks) the same way Soulver (a Mac App) does

Soulver is a great scratch pad for math that allows you to wr开发者_开发知识库ite expressions in a very natural form, which makes it versatile and fun to use in many occasions. There's a short video on the site that displays a lot of its functionality.

I'd like to tackle writing a parser that behaved much as that of that app's. For instance, if you go shopping, you can write a big list like

2 * 1.99 soap + 2.99 cereal + 39.59 organic magic beans 

and see, as you type, the sum of what's in the line (46.56).

You can also create variables, such as

March = 2 * 1.99 soap + 2.99 cereal + 39.59 organic magic beans 

and reference them in later operations. Other operators, such as 'off' (40% off $200), also exist.

Considering it has some level of sophistication and it should distinguish meaningful terms while ignoring some of the input, what sort of grammar should I be using to represent this little language? I could probably cobble some spaghetti regex together, but I'd honestly like to do something a little better, even if it requires a lot of study from my part. What would you recommend?


A regexp by itself is likely not expressive enough to the job if you want to model real mathematics, e.g., anything with nested parentheses.

Context-free grammars are remarkably expressive. You should learn about Backus Normal Form (BNF), a means for writing down the description of languages as context-free grammars.
You can choose from among many parser generator tools, to convert that grammar into a real parser.

Which specific grammar you write depends on what you want the expressions to mean, and which atoms in the expression really get ignored. As a practical matter, the way you write the BNF varies from tool to tool, so choosing your parser generator tool first will save you the trouble of rewriting your BNF later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜