Reputation: 499
I am now using ocaml to deal with some arithmetic expressions. If every arithmetic expression is a string like: "1+2*(2-5)". I want to know how to use ocaml to eliminate useless parentheses.
For example if we get a string like "(2*(1-8))" we should output "2*(1-8)".
Thanks.
Upvotes: 0
Views: 556
Reputation: 66803
OCaml is just a programming language, not a symbolic algebra system. So you would solve this in OCaml just as in any general purpose language.
A full blown solution would be to parse the expression into a tree, then walk the tree to produce the output. For this you need to analyze your string lexically (for which you can probably use the Str
module), and then parse the tokens. You can code your own parser pretty easily, or you could really go full force and use a parser generator like ocamlyacc
.
For the relatively simple problem of reparenthesizing an arithmetic expression you can use a variant of the "shunting yard" algorithm, which in essence calculates a canonical, unparenthesized (RPN) form of an expression.
Upvotes: 2