是否有一种直接的方式将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."
Run Code Online (Sandbox Code Playgroud)
我正在寻找如何实施fun_to_str.在javascript中,一些解释器具有.toSource()可以在任何对象上调用的函数,包括打印其字符串表示的函数.任何信息表示赞赏,谢谢.
Ada*_*erg 16
首先,获取有趣的环境变量(包括抽象代码):
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}]}]}]}]}
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
(你必须添加{'fun', 1, {clauses, ...}}它以使其成为一个完整的Erlang表达式)