Erlang 将元组转换为属性列表

Erlang 将元组转换为属性列表,erlang,Erlang,如何从MongoDB转换元组 {'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined} {u id',密码,年龄,未定义} 支持列表 [{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}] [{u id',},{password,},{age,undefined}] 假设您希望基

如何从MongoDB转换元组

{'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}
{u id',密码,年龄,未定义}
支持列表

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

假设您希望基本上将元组的两个连续元素组合在一起,这并不难。可以使用从元组中提取元素。并获得元组的大小。这里有两种处理方法:

1> Tup = {'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}.
{'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}
2> Size = tuple_size(Tup).            
6
1>Tup={u id',密码,年龄,未定义}。
{u id',密码,年龄,未定义}
2> 大小=元组大小(Tup)。
6.
您可以使用列表理解:

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

3>[{element(X,Tup),element(X+1,Tup)}| | X列表:zip([element(X,Tup)| | X或者,您可以编写一个简单的函数来执行此操作:

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)].

这基本上就是列表理解版本所做的,但分解成一个显式循环。

效率不高,因此不要在大型结构上使用它,但非常简单:

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]).

如果出于某种奇怪的原因,顺序应该是重要的,那么在to_proplist1/2的基本情况下反转proplist。

您可以使用bson:fields/1()。bson是mongodb erlang驱动程序的依赖关系

它不必是尾部递归的,所以
到_proplist([])->到_proplist([K,V | t])->[{K,V}到|到_proplist(t)].
因为这种递归现在已经足够快了,而且元组的大小已经很有限。事实上,它不必是尾部递归的,但一般来说,使用累积参数的尾部递归版本会减少尖峰内存的使用。对于这个特定的函数,当然,如果我们有足够长的列表来存储太慢了。看起来应该改变的是mongodb。我也做了同样的事情,而且在我看来每个人都做了。所以也许mongodb驱动程序毕竟应该这样做。
5> lists:zip(slice(Tup, 1, Size, 2), Slice(Tup, 2, Size, 2)).
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]
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)].
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]).