连接erlang中元组中保存的值

时间:2012-12-11 20:42:21

标签: erlang mapreduce riak

我正在尝试在erlang中为riak编写一个map阶段,我遇到了问题。我需要连接一个描述和一个代码,它们是单独的项目,并以“代码描述”的形式组合,然后需要给它一个值1,所以“代码描述”= 1,以便我可以计算在我的reduce阶段中出现相同的情况(描述来自静态池,而不是自由文本)。破折号也很重要。使用proplists我可以导航到我想要的值并使用{struct,values} = ...等我得到了一些东西:

[{"desc":"Stuff Needs Doing","code":"SND"},{"desc":"Done","code":"DNE"}]

当我编写以下代码片段时,我只会在我的过滤列表中为每个kv返回desc:

Desc = proplists:get_value(<<"desc">>, Data),
[Desc].

看到它们是如何两个字符数据我认为[DescVar ++ CodeVar]。会工作,但当我对我的集群运行它时,我实际上收到了一条错误消息,它抱怨++。 +也不起作用,我怎么做我在erlang之后的事情?

2 个答案:

答案 0 :(得分:1)

我不认为您的输入示例在Erlang中有效。

然而,作为一个例子,如果你的输入是这样的:

[{"desc","A","code","B"}, {"desc","A","code","B"}, {"desc","C","code","B"}]

然后这确实是你想要的:

test() ->
    do([{"desc","Stuff Needs Doing","code","SND"},{"desc","Done","code","DNE"},{"desc","Done","code","DNE"}]).

do(L) -> 
    L2 = lists:map(fun({_,D,_,C}) -> C++"-"++D end, L),
    count(L2,[]).

count([], Acc) -> Acc;
count([H|T], Acc) -> 
    case lists:keytake(H,1,Acc) of
        false -> count(T, [{H,1} | Acc]);
        {value, {H,N}, Acc2} -> count(T, [{H,N+1} | Acc2])
    end.

输出:

1> test:test().
[{"DNE-Done",2},{"SND-Stuff Needs Doing",1}]
2> 

答案 1 :(得分:1)

我没有玩过Riak,但我假设你正在使用典型的erlang解码json([{struct,Values}]格式)。

[{"desc":"Stuff Needs Doing","code":"SND"},{"desc":"Done","code":"DNE"}]

上面的json字符串将解码为erlang:

[{struct,[{<<"desc">>,<<"Stuff Needs Doing">>},
      {<<"code">>,<<"SND">>}]},
{struct,[{<<"desc">>,<<"Done">>},{<<"code">>,<<"DNE">>}]}]

然后这个List理解会给你你想要的结果(并保持正确的结果格式):

[{struct,[{<<X/binary,"-",Y/binary>>,1}]}||{struct,[{<<"desc">>,Y},{<<"code">>,X}]}<-Data].

“Data”是erlang解码的JSON。

这会产生:

[{struct,[{<<"SND-Stuff Needs Doing">>,1}]},{struct,[{<<"DNE-Done">>,1}]}]

将JSON字符串编码为:

[{"SND-Stuff Needs Doing":1},{"DNE-Done":1}]