【问题标题】:Erlang -- How to convert a fun() object to a StringErlang -- 如何将 fun() 对象转换为字符串
【发布时间】:2011-07-12 03:46:42
【问题描述】:

有没有一种直接的方法可以将 Erlang fun 转换为 string?对io_lib:format 的调用仅打印函数引用,例如类似"#Fun<erl_eval.20.67289768>"。例如,我希望能够做到这一点:

1> Fun = fun() -> atom_to_list('hello world') end.
2> FunStr = fun_to_str(Fun).
"fun() -> atom_to_list('hello world') end."

我正在寻找如何实现fun_to_str。在 javascript 中,一些解释器有一个 .toSource() 函数,可以在任何对象上调用,包括打印其字符串表示的函数。感谢您提供任何信息,谢谢。

【问题讨论】:

    标签: erlang


    【解决方案1】:

    你也许可以使用 erlang:fun_info/2 来做这件事,至少我在做的时候从 shell 中得到了一些信息

    1> erlang:fun_info(fun() -> test,ok end, env).
    {env,[[],
         {value,#Fun<shell.7.37281544>},
         {eval,#Fun<shell.24.85590193>},
         [{clause,1,[],[],[{atom,1,test},{atom,1,ok}]}]]}
    2>
    

    你想要最后一个带有子句 atom 的列表,然后使用例如 erl_pp 漂亮地打印它

    【讨论】:

      【解决方案2】:

      首先,获取乐趣的环境变量(包括抽象代码):

      1> {env, [{_, _, _, Abs}]} = erlang:fun_info(Fun, env).                     
      {env,[{[],
             {eval,#Fun<shell.21.83096281>},
             {value,#Fun<shell.5.83096281>},
             [{clause,1,[],[],
                      [{call,1,{atom,1,atom_to_list},[{atom,1,hello_world}]}]}]}]}
      

      使用erl_pp漂亮地打印抽象代码:

      3> Str = erl_pp:expr({'fun', 1, {clauses, Abs}}).           
      [[[["fun",
          [[[[["()"]," ->"],
             ["\n       ",
              [["atom_to_list",[[40,["'hello world'",41]]]]]]]]]]],
        [10,["end"]]]]
      4> io:format([Str|"\n"]).
      fun() ->
             atom_to_list('hello world')
      end
      ok
      

      (您必须在其周围添加{'fun', 1, {clauses, ...}} 以使其成为完整的Erlang 表达式)

      【讨论】:

      • 在实践中,这非常有效,但有时我会写一个不平凡的fun 并使用此方法将其转换为字符串产生以下内容:fun()-&gt; end 没有正文。关于可能导致此问题的任何想法?
      • 不平凡的乐趣是什么意思?能举个例子吗?
      • 内心深处的任何乐趣;我可以在 shell 中运行你的命令并且它可以工作,但是在我的程序中做同样的事情却不行。 fun_info 步骤不返回除 funend 之外的标记,即使该函数在语法上是正确的并且可以编译等等
      • 编译代码中的乐趣只是对编译到定义它们的模块中的隐藏函数的引用。您是否尝试使用选项 debug_info 编译模块?
      • 在 17RC2 +debug_info 似乎没有任何改变。
      猜你喜欢
      • 2021-02-03
      • 2018-07-19
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多