Erlang - 如何将fun()对象转换为String [英] Erlang -- How to convert a fun() object to a String
问题描述
有没有一个直接的方式来将Erlang fun
转换为字符串
?调用 io_lib:format
仅打印函数引用,例如。像#Fun< erl_eval.20.67289768>
。例如,我想要这样做:
Is there a straightforward way to convert an Erlang fun
to a string
? A call to io_lib:format
only prints the function reference, e.g. something like "#Fun<erl_eval.20.67289768>"
. For example, I'd like to be able to do this:
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()
函数,可以在打印其字符串表示的任何对象(包括函数)上调用。谢谢,谢谢。
I'm looking for how to implement fun_to_str
. In javascript, some interpreters have a .toSource()
function that can be called on any object, including functions, that print their string representation. Any info is appreciated, thanks.
推荐答案
首先,获取有趣的环境变量(包括抽象代码):
First, get the environment variables for the fun (which includes the abstract code):
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表达式)
(You have to add {'fun', 1, {clauses, ...}}
around it to make it a complete Erlang expression)
这篇关于Erlang - 如何将fun()对象转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!