[erlang-questions] Function to print a record with fieldnames?

Claes Wikstrom klacke@REDACTED
Tue Mar 11 13:32:10 CET 2008


Mats Cronqvist wrote:
> Convey Christian J NPRI wrote:
>> I've got a record definition along the lines of:  -record(myrec, {foo 
>> = undefined, bar=undefined}).
>

We have this in some code: It's not especially good but works.

1. in a .hrl file

%% Used to print records nicely as in
%% io:format("Just got ~s\n", [?format_record(Message, message)]),
-define(format_record(Rec, Name),
         misc:format_record(Rec, Name, record_info(fields, Name))).



2. And then in a module ......


%% returns {record, RecName, [Field1, Val1} .....]
format_record(Record, Name, Fields) ->
     case tuple_to_list(Record) of
         [Name | Rest] ->
             io_lib:format("record ~w {\n~s", [Name,
                                             format_record(Rest, Fields)]);
         _X ->
             "badrecord"
     end.

format_record([], []) ->
     [];
format_record([Val|Vals], [F|Fs]) when is_integer(Val);
                                        Val == [];
                                        atom(Val);
                                        is_float(Val)->
     Curly = if Vals == [] -> " }";
                true -> ","
             end,
     [io_lib:format("     ~w = ~w~s\n", [F,Val,Curly]),
      format_record(Vals, Fs)];
format_record([Val|Vals], [F|Fs]) ->
     case is_string(Val) of
         true ->
             [io_lib:format("     ~w = ~s\n", [F,Val]),
              format_record(Vals, Fs)];
         false ->
             [io_lib:format("     ~w = ~p~n", [F, Val]),
              format_record(Vals, Fs)]
     end.

is_string(L) when list(L) ->
     all_integer(L);
is_string(_) ->
     false.

all_integer([H|T]) when is_integer(H),
                         $A < H, H < $z ->
     all_integer(T);
all_integer([_|_]) ->
     false;
all_integer([]) ->
     true.



More information about the erlang-questions mailing list