[erlang-questions] Converting list of tagged tuples to a record
Rapsey
rapsey@REDACTED
Thu Sep 2 17:32:16 CEST 2010
I use these two functions (rec2prop, prop2rec):
rec2prop(Rec, RecordFields) ->
loop_rec(RecordFields, 1, Rec, []).
loop_rec([H|T], N, Rec, L) ->
loop_rec(T, N+1, Rec, [{H, element(N+1, Rec)}|L]);
loop_rec([], _, _, L) ->
L.
prop2rec(Prop, RecName, DefRec, RecordFields) ->
loop_fields(erlang:make_tuple(tuple_size(DefRec), RecName),
RecordFields, DefRec, Prop, 2).
loop_fields(Tuple, [Field|T], DefRec, Props, N) ->
case lists:keysearch(Field, 1, Props) of
{value, {_, Val}} ->
loop_fields(setelement(N, Tuple, Val), T, DefRec, Props, N+1);
false ->
loop_fields(setelement(N, Tuple, element(N, DefRec)), T, DefRec,
Props, N+1)
end;
loop_fields(Tuple, [], _, _, _) ->
Tuple.
And then for every record a define (#cdat{} is the name of the record):
-define(R2P(Record), rec2prop(Record, record_info(fields, cdat))).
-define(P2R(Prop), prop2rec(Prop, cdat, #cdat{}, record_info(fields,
cdat))).
It's not exactly optimal, but at least I don't have to write a function for
every record (just two short defines).
Sergej
On Thu, Sep 2, 2010 at 8:48 AM, Bengt Kleberg <bengt.kleberg@REDACTED>wrote:
> Greetings,
>
> After 10 years of programming Erlang I still use the method described
> below (1) when moving data from a user interface.
> The same goes for using records in records. It is rather awkward to
> update the innermost records, so it helps to use functions.
>
>
> bengt
>
> On Thu, 2010-09-02 at 08:23 +0200, Silas Silva wrote:
> > Hello all,
> >
> > In my newbie application, I receive a bunch of data from HTTP's POST
> > (I'm using Mochiweb), in the following format (supposing a person's
> > data):
> >
> > [{first_name, value}, {last_name, value}, ...]
> >
> > And I have the definition of the record for the person:
> >
> > -record(person, {first_name, last_name, ...}).
> >
> > alistair in the #erlang channel in freenode, gave me a nice solution to
> > put this list in the record:
> >
> > lists:foldl(fun add_to_record/2, #person{}, List).
> >
> > add_to_record({first_name, value}, rec) ->
> > rec#person{first_name = value};
> >
> > add_to_record({last_name, value}, rec) ->
> > rec#person{last_name = value};
> >
> > ...
> >
> > That works. My questions are:
> >
> > 1. Are there other [good practice] ways to transform information coming
> > from a UI (which, must of the times, come as a list) in well
> > specified records?
> >
> > 2. Is it common to use records of records? Is it possible? For example:
> >
> > -record(name, {last_name, first_name}).
> > -record(person, name, ...)
> >
> > Thanks!
> >
>
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
>
More information about the erlang-questions
mailing list