Search code examples
erlangrecords

Erlang record to tuple list


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?


Solution

  • 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)))).