How to turn a list of tuple pairs into an entry in Erlang?

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 to convert Keyvalpairs to Foorecord?

+4
source share
3 answers

The easiest way to do this:

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)]]). 
+17
source

Like the other answers, you need to flip your own solution to accomplish this. However, the proposed solutions are incomplete. For example, it does not consider default values โ€‹โ€‹for record entries. I use the following code snippet to take care of this conversion:

 %% @doc returns a "RECSPEC" that can be used by to_rec in order to %% perform conversions -define(RECSPEC(R), {R, tuple_to_list(#R{}), record_info(fields, R)}). %% @doc converts a property list into a record. -spec to_rec(recspec(), proplist()) -> record(). to_rec({R, [_ | N], Spec}, P) when is_atom(R) and is_list(Spec) -> list_to_tuple( [R | lists:foldl( fun ({K,V}, A) -> case index_of(K, Spec) of undefined -> A; I -> {Head, Tail} = lists:split(I, A), Rest = case Tail of [_ | M] -> M; [] -> [] end, Head ++ [V | Rest] end end, N, P)]). 

Now you can simply do:

 -record(frob, {foo, bar="bar", baz}). to_rec(?RECSPEC(frob), [{baz, "baz"}, {foo, "foo"}]) 

what gives

 #frob{foo="foo", bar="bar", baz="baz"} 

I put this in a small โ€œtoolkitโ€ library that I am going to compile for these small โ€œsnippetsโ€ that just make life easier when developing Erlang applications: ETBX

+3
source

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

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

All Articles