[erlang-questions] Iteration over records/record fields ?

jla415 jla415@REDACTED
Sun Nov 5 16:28:04 CET 2006


since record_info is evaluated at compile time you will need to setup a
function to map your records to fields and use that to look up the name and
order of the fields

fields(person) -> record_info(fields, person);
fields(place) -> record_info(fields, place);
fields(thing) -> record_info(fields, thing).

and use that to do your mapping... eg:

erlang:list_to_tuple([RecType] ++ lists:map(fun(X) -> proplists:get_value(X,
RecProps) end, fields(RecType)).


Désiré Cocoyer wrote:
> 
> Hi,
> 
> For a project of mine, I have to import some XML elements into a bunch 
> of Mnesia tables. Each record I defined map exactly to the structure of 
> each XML element.
> 
> Example :
> 
> XML :
> <person>
>   <name>Simpson</name>
>   <firstname>Homer J.</firstname>
>   ...
> </person>
> 
> <house>
>   <address>742 Evergreen T.</address>
>   <coordinates>42.293,12.942,0<coordinates>
>   ...
> </house>
> 
> after parsing and transformation, I get a list like :
> [{person, [{name, "Simpson"}, {firstname, "Homer J."}, ... ]},
> {house, [{address, "742 Evergreen T."}, {coordinates, 
> "42.293,12.942,0"}, ...],
> ... ]
> 
> The corresponding record I define :
> -record(person, { name = [], firstname = [], ... }).
> -record(house, { address = [], coordinates = [], .... }).
> ...
> 
> The problem is that I have an important list of records defined (about 
> 30), each having about 20 to 40 fields.
> How can I programmatically iterate over my list  to populate my records ?
> 
> I wish I could write #RecordName.Field or record_info(fields, 
> RecordName), with RecordName and Field being variables, and iterate in 
> list comprehensions and lists:foldl but that doesn't seem possible. Is 
> there a way around ? (I wish I could also avoid macros. ^^). I also 
> heard of the Smerl trickery, is that the way to go ?
> 
> Thanks
> 
> igwan
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 
> 

-- 
View this message in context: http://www.nabble.com/-erlang-questions--Iteration-over-records-record-fields---tf2577510.html#a7186073
Sent from the Erlang Questions mailing list archive at Nabble.com.





More information about the erlang-questions mailing list