Fun = fun() -6ren">
gpt4 book ai didi

Erlang——如何将 fun() 对象转换为字符串

转载 作者:行者123 更新时间:2023-12-02 07:31:49 24 4
gpt4 key购买 nike

有没有一种简单的方法来转换 Erlang funstring ?调用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()可以在任何对象上调用的函数,包括打印其字符串表示形式的函数。如有任何信息,我们将不胜感激,谢谢。

最佳答案

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

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 表达式)

关于Erlang——如何将 fun() 对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5250587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com