I just came across this post,it's quite elegant.
But it's not taking into account the priority of different operators.
e.g. *
has higher priority than +
.
So 1+2*(3+2)
should be converted to 1 2 3 2 + * +
How to do it in erlang taking the priority issue into account?
Here is a way to do it which abuses the built-in parser for Erlang terms. You could write your own parser via yecc or recursive descent, but for the simplicity, I'll stick with the Erlang-parser.
-module(foo).
-compile(export_all).
Declare a module, export everything from it. This is bad form if you want to use this. Rather minimize the export to p/1
.
parse(Str) ->
{ok, Tokens, _} = erl_scan:string(Str ++ "."),
{ok, [E]} = erl_parse:parse_exprs(Tokens),
E.
This function abuses the Erlang parser so we can get a parse tree of Erlang tokens.
rpn({op, _, What, LS, RS}) ->
rpn(LS),
rpn(RS),
io:format(" ~s ", [atom_to_list(What)]);
rpn({integer, _, N}) ->
io:format(" ~B ", [N]).
RPN output is to do a post-order tree-walk traversal. So we basically walk the Left hand and right hand side of the tree and then output ourselves as a node. The order of "parenthesis" is stored abstractly in the tree itself. The priority is handled by the Erlang parser. You could easily do this via a recursive descent parser if you want. But that is a different question to the point of "How do I write parsers in Erlang?" The answer is twofold: Either you use leex+yecc or you use a parser based upon parser combinators and/or recursive descent. Especially for a grammar this simple.
p(Str) ->
Tree = parse(Str),
rpn(Tree),
io:format("~n").
This is just formatting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With