Convert tuples to proplists

2019-06-24 06:52发布

问题:

How can I convert tuple from MongoDB

{'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}

to proplist

[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]

回答1:

Assuming you want to basically combine the two consecutive elements of the tuple together, this isn't too hard. You can use element\2 to pull elements from tuples. And tuple_size\1 to get the size of the tuple. Here's a couple of ways to handle this:

1> Tup = {'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}.
{'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}
2> Size = tuple_size(Tup).            
6

You can use a list comprehension for this:

3> [{element(X, Tup), element(X+1, Tup)} || X <- lists:seq(1, Size, 2)].
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]

Or you can zip it:

4> lists:zip([element(X, Tup) || X <- lists:seq(1, Size, 2)], [element(X, Tup) || X <- lists:seq(2, Size, 2)]).
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]

You can clean up that zip by making a function to handle pulling elements out.

slice(Tuple, Start, Stop, Step) ->
    [element(N, Tuple) || N <- lists:seq(Start, Stop, Step)].

Then calling this function:

5> lists:zip(slice(Tup, 1, Size, 2), Slice(Tup, 2, Size, 2)).
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]


回答2:

You can use bson:fields/1 (https://github.com/mongodb/bson-erlang/blob/master/src/bson.erl#L52). bson is the dependency of mongodb erlang driver



回答3:

Alternatively you could write a simple function to do it:

mongo_to_proplist(MongoTuple) ->
    mongo_to_tuple(MongoTuple, 1, tuple_size(MongoTuple)).

mongo_to_proplist(Mt, I, Size) when I =:= Size -> [];
mongo_to_proplist(Mt, I, Size) ->
    Key = element(I, Mt),
    Val = element(I+1, Mt),
    [{Key,Val}|mongo_to_proplist(Mt, I+2, Size)].

This is basically what the list comprehension versions are doing but unravelled into an explicit loop.



回答4:

Not very efficient, so do not use it on large structures, but really simple:

to_proplist(Tuple) -> to_proplist1(tuple_to_list(Tuple), []).

to_proplist1([], Acc) -> Acc;
to_proplist1([Key, Value | T], Acc) -> to_proplist1(T, [{Key, Value} | Acc]).

If order should for some strange reason be important reverse the proplist in the base case of to_proplist1/2.



标签: erlang