Search code examples
erlanginfix-notationrpnerlpostfix-notation

In Erlang, how to return a string when you use recursion?


I really could'n formulate the question better, but here's my problem: I want to use this code to convert infix expression to postfix expression in Erlang, but it only writes to the console output. The problem is, I need a list or a string returned, so I can use it as an argument in an other function.

-module(foo).
-compile(export_all).

parse(Str) ->    
    {ok, Tokens, _} = erl_scan:string(Str ++ "."),
    {ok, [E]} = erl_parse:parse_exprs(Tokens),
    E.

rpn({op, _, What, LS, RS}) ->
    rpn(LS),
    rpn(RS),
    io:format(" ~s ", [atom_to_list(What)]);
rpn({integer, _, N}) ->
    io:format(" ~B ", [N]).

p(Str) ->
    Tree = parse(Str),
    rpn(Tree),
    io:format("~n").

For example, I want someting like this:

Str = "2 * (3 + 4)".
module:p(Str) =:= "2 3 4 + *".
module:anotherFunction(p(Str)).

Solution

  • You just need to io_lib:format/2 instead of io:format/2 and lists:flatten/1 in the end.

    -module(foo).
    -compile(export_all).
    
    parse(Str) ->
        {ok, Tokens, _} = erl_scan:string(Str ++ "."),
        {ok, [E]} = erl_parse:parse_exprs(Tokens),
        E.
    
    rpn({op, _, What, LS, RS}) ->
        io_lib:format("~s ~s ~s", [rpn(LS), rpn(RS), atom_to_list(What)]);
    rpn({integer, _, N}) ->
        io_lib:format("~b", [N]).
    
    p(Str) ->
        Tree = parse(Str),
        lists:flatten(rpn(Tree)).