【问题标题】:In Erlang, how to return a string when you use recursion?在 Erlang 中,使用递归时如何返回一个字符串?
【发布时间】:2013-06-30 14:18:36
【问题描述】:

我真的无法更好地提出这个问题,但这是我的问题: 我想在 Erlang 中使用this 代码将中缀表达式转换为后缀表达式,但它只写入控制台输出。问题是,我需要返回一个列表或字符串,所以我可以将它用作其他函数的参数。

-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").

例如,我想要这样的东西:

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

【问题讨论】:

    标签: erlang infix-notation rpn erl postfix-notation


    【解决方案1】:

    最后你只需要io_lib:format/2 而不是io:format/2lists:flatten/1

    -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)).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      相关资源
      最近更新 更多