Erlang 记录到元组列表

发布于 2024-12-28 12:53:56 字数 410 浏览 5 评论 0原文

我正在尝试制定一个宏定义,将记录转换为元组列表。类似于:

> Id = #id{id1=1,id2=2,id3=3}.
{id,1,2,3}
> ?record_to_tuplelist(id,Id).
[{id1,1},{id2,2},{id3,3}]

到目前为止,我已经解决了这个问题:

-define(record_to_tuplelist(Rec,RecRef), [ {X,RecRef#Rec.X} || X <- record_info(fields,Rec) ]).

但它给出了语法错误。如果我将 RecRef#Rec.X 更改为 RecRef#Rec{} 它可以工作,但不会返回我想要的内容。这只是一个晦涩的语法错误还是实际上不可能?

I'm trying to work out a macro definition that will turn a record into a tuple list. Something like:

> Id = #id{id1=1,id2=2,id3=3}.
{id,1,2,3}
> ?record_to_tuplelist(id,Id).
[{id1,1},{id2,2},{id3,3}]

So far I worked out this:

-define(record_to_tuplelist(Rec,RecRef), [ {X,RecRef#Rec.X} || X <- record_info(fields,Rec) ]).

But it gives a syntax error. If I change RecRef#Rec.X to RecRef#Rec{} it works, but doesn't return what I want. Is this just an obscure syntax error or is this actually not possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝戈者 2025-01-04 12:53:56

不,记录名称和字段名称都必须是原子。怎么样(未经测试):

-define(record_to_tuplelist(Rec, Ref), lists:zip(record_info(fields, Rec),tl(tuple_to_list(Ref)))).

No, both the record name and the field names have to be atoms. How about something like (untested):

-define(record_to_tuplelist(Rec, Ref), lists:zip(record_info(fields, Rec),tl(tuple_to_list(Ref)))).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文