[erlang-questions] Function to print a record with fieldnames ?
Mats Cronqvist
mats.cronqvist@REDACTED
Wed Mar 5 09:35:43 CET 2008
Convey Christian J NPRI wrote:
> Thanks Mats,
>
> That works great for me.
>
> Could you explain something to me please? :
>
> Why must this be a macro rather than a function? It seems that if I want rec_info to be a function rather than a macro, record_info's second parameter must be a hard-coded atom; it cannot be a variable. But nothing I've read in Armstrong's book led me to think that such a restriction was possible in Erlang.
>
because record_info, weirdly enough, is a (built-in) macro.
to expand (haha) a bit, the compiler will automatically generate 2
functions, module_info/{0,1}, and expand some macros (?LINE, ?MODULE,
record_info, perhaps others?) on the plus side, afaik record_info is the
only such cleverly disguised macro.
mats
> Thanks,
> Christian
>
>
>> -----Original Message-----
>> From: Mats Cronqvist [mailto:mats.cronqvist@REDACTED]
>> Sent: Tuesday, March 04, 2008 9:53 AM
>> To: Convey Christian J NPRI
>> Cc: erlang-questions@REDACTED
>> Subject: Re: [erlang-questions] Function to print a record
>> with fieldnames?
>>
>> Convey Christian J NPRI wrote:
>>
>>> I've got a record definition along the lines of:
>>>
>> -record(myrec, {foo = undefined, bar=undefined}).
>>
>>> To help with debugging, I'd like a function that will print
>>>
>> out something like the following text:
>>
>>> #record{foo = 42, bar = the_answer_to_the_question}
>>>
>>> Does such a function exist, or must I write my own version
>>>
>> of the function for each record type? I know I can just use
>> io:format("~p~n", [ MyRecord ]), but I'd really like the
>> fieldnames to also be printed.
>>
>>>
>>>
>> best i've seen is variations on this theme;
>>
>> -module('foo').
>> -author('Mats Cronqvist').
>> -export([go/0]).
>>
>> -define(rec_info(T,R),lists:zip(record_info(fields,T),tl(tuple
>> _to_list(R)))).
>> -record(r,{bla,foo,baz,bar}).
>>
>> go() -> ?rec_info(r,#r{}).
>>
>>
>>
>>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: mats_cronqvist.vcf
Type: text/x-vcard
Size: 179 bytes
Desc: not available
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080305/4868e476/attachment.vcf>
More information about the erlang-questions
mailing list