tags:

views:

432

answers:

2

Let's say I have this:

-record(my_record, {foo, bar, baz}).

Keyvalpairs = [{foo, val1},
               {bar, val2},
               {baz, val3}].

Foorecord = #my_record{foo=val1, bar=val2, baz=val3}.

How do I convert Keyvalpairs into Foorecord?

+8  A: 

The simplest thing to do is:

Foorecord = #my_record{foo=proplists:get_value(foo, Keyvalpairs), 
      bar=proplists:get_value(bar, Keyvalpairs),
      baz=proplists:get_value(baz, Keyvalpairs)}.

If this is too repetitive you can do something like:

Foorecord = list_to_tuple([my_record|[proplists:get_value(X, Keyvalpairs)
      || X <- record_info(fields, my_record)]]).
cthulahoops
A: 

If you have the values in the same order as in the record, you can convert directly into the record, you just need to precede the name of the record at the first element of the list and then convert the list into a tuple.

Foorecord = list_to_tuple([my_record]++[Val || {_,Val} <- [{foo, val1},{bar, val2},{baz, val3}] ]).
ramontiveros