[erlang-questions] Converting list of tagged tuples to a record

Evans, Matthew <>
Thu Sep 2 20:56:39 CEST 2010


Using a preprocessor is another, perhaps more generic way of doing it.





%% The record

-record(person, {first_name, last_name, ...}).





%% Create a preprocessor

-define(PERSON_RECORD,record_info(fields, person)).





%% Function that will convert a list of tuples to the record

create_record_from_list([],_Data,Result) ->

    erlang:list_to_tuple(Result);

create_record_from_list([Field|Rest],Data,Result) ->

    case lists:keysearch(Field,1,Data) of

        {value,{_,Value}} ->

            create_record_from_list(Rest,Data,lists:append(Result,[Value]));

        _ ->

            create_record_from_list(Rest,Data,lists:append(Result,[undefined]))

    end.







Then to convert the list of tuples "DataList" to a record call:



Record = create_record_from_list(?PERSON_RECORD,DataList,[person]),





Or something like that :)



Matt



-----Original Message-----
From:  [mailto:] On Behalf Of Silas Silva
Sent: Thursday, September 02, 2010 2:24 AM
To: 
Subject: [erlang-questions] Converting list of tagged tuples to a record



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!



--

Silas Silva



________________________________________________________________

erlang-questions (at) erlang.org mailing list.

See http://www.erlang.org/faq.html

To unsubscribe; mailto:




More information about the erlang-questions mailing list