How to convert infix to postfix in erlang?

我只是一个虾纸丫 提交于 2019-12-12 09:39:19

问题


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?


回答1:


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.




回答2:


You can get inspired by mine Erlang Programming Exercise 3-8 solution. There is all handwritten lexer, parser and "compiler" to postfix code.

Edit: Sorry, I see Exercise 3-8 has explicit bracketing so it doesn't solve operator priority. You would have to modify parser to handle it.



来源:https://stackoverflow.com/questions/7242315/how-to-convert-infix-to-postfix-in-erlang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!