[erlang-questions] Record field position number?
Juan Jose Comellas
juanjo@REDACTED
Fri Mar 9 16:34:37 CET 2012
You could use the following module that contains a parse transform for what
you need:
https://github.com/jcomellas/mlapi/blob/master/src/dynarec.erl
When you include it in a module it will automatically create the functions
that you need to access the records and fields defined in your module by
name. To include it in the module where you have defined the records you do:
-compile([{parse_transform, dynarec}]).
The functions that will now be available are:
get_value(field_name, Record) ->
Record#record_name.field_name.
set_value(field_name, Value, Record) when is_record(Record, record_name) ->
Record#record_name{field_name = Value}.
records() ->
[record_name1, record_name2, ...].
fields(record_name) ->
[field_name1, field_name2, ...].
new_record(record_name) ->
#record_name{}.
Hope it helps,
Juanjo
On Fri, Mar 9, 2012 at 12:20 PM, Max Bourinov <bourinov@REDACTED> wrote:
> Hi Erlangers,
>
> Is there is a way to find a position number of the field in the record:
>
> 1. At compile time (record_info)?
> 2. At runtime (I think not).
>
> Motivation:
> I use lists module and its functions like lists:keyfind/3 for dealing with
> records. I don't want to hardcode number to target certain record's field.
> I afraid that if I change order of fields in my records my code will be
> broken (It will be indeed). So, I do believe that it is possible to do
> something like:
>
> ...
> -record(my_rec {
> name, age, gender
> }).
> %
> ListOfRecords = [#my_rec{name = "John"}, #my_rec{name =
> "Peter"}, #my_rec{name = "Marry"}],
> Value = "Peter",
> %
> case lists:keyfind(Value, ?get_filed_number(name, my_rec), ListOfRecords)
> of
> ...
>
> I hope it is possible to define some sort of makro that will do the job...
>
> Any ideas?
>
> Best regards,
> Max
>
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120309/ffe77cab/attachment.htm>
More information about the erlang-questions
mailing list