Erlang列表中的元组列表中包含另一个元组列表

时间:2014-07-25 07:50:43

标签: list map erlang tuples

所以,我正在寻找一种很好的方法来做到这一点。

传入数据就像(它可以远远超过示例,但只有一个子级):

[
  [
    {d1, "1"}, 
    {d2, "2"}, 
    {sub_data,
      [
        {d1, "3"},
        {d2, "4"}
      ]
    }
  ], 
  [
    {d1, "5"},
    {d2, "6"}
  ]
]

我需要将其序列化为:

  

[{" 1"," 2"},{"> 3","> 4"},{" 5"," 6"}]

现在我这样做,这不是一个很好的方式imo:

lists:map(fun(Data) ->
    [{f:g(d1, Data), f:g(d2, Data)}] ++
    [{"> " ++ f:g(d1, SubData)}, {"> " ++ f:g(d2, SubData)} 
     || SubData <- f:g(sub_data, Data)], 
    Data
).

2 个答案:

答案 0 :(得分:0)

以下是我的想法:

transform(Input) ->
        lists:flatten(lists:map(fun(Item) -> transform_item(Item, []) end, Input)).

transform_item(Item, Prefix) ->
        {KVs, SubDatas} = lists:partition(fun({sub_data, _}) -> false;
                                             (_) -> true
                                          end, Item),
        Res0 = list_to_tuple(lists:map(fun({_, Value}) -> Prefix ++ Value end, KVs)),
        [Res0, lists:map(fun({sub_data, SubItem}) -> transform_item(SubItem, "> ") end, SubDatas)].

test() ->
        case transform([[{d1, "1"}, {d2, "2"}, {sub_data, [{d1, "3"}, {d2, "4"}]}], [{d1, "5"}, {d2, "6"}]]) of
                [{"1", "2"}, {"> 3", "> 4"}, {"5", "6"}] -> io:format("SUCCESS");
                InvalidResult -> io:format("FAILED. Result=~p", [InvalidResult])
        end.

答案 1 :(得分:0)

我在评论中的意思是,很难知道如何推广输入。例如,可以想象您的输入被定义为具有以下结构的元素列表:

[{d1,V},{d2,V}] or
[{d1,V},{d2,V},{subdata,[{d1,V},{d2,V}]}]

在这种情况下,您可以使用函数进行转换:

1> F = fun(L) -> lists:reverse(lists:foldl(
            fun([{_,V1},{_,V2},{sub_data,[{_,V3},{_,V4}]}],Acc) -> [{"> " ++ V3,"> " ++ V4},{V1,V2}|Acc];
               ([{_,V1},{_,V2}],Acc) -> [{V1,V2}|Acc] end,
            [],L)) end.
#Fun<erl_eval.6.106461118>
2> F([[{d1,"1"},{d2,"2"},{sub_data,[{d1,"3"},{d2,"4"}]}],[{d1,"5"},{d2,"6"}]]).
[{"1","2"},{"> 3","> 4"},{"5","6"}]
3> F([[{d1,"1"},{d2,"2"},{sub_data,[{d1,"3"},{d2,"4"}]}],
      [{d1,"5"},{d2,"6"}],
      [{d1,"7"},{d2,"8"},{sub_data,[{d1,"9"},{d2,"10"}]}]]).
[{"1","2"},{"> 3","> 4"},{"5","6"},{"7","8"},{"> 9","> 10"}]
4>

但是,如果可能有任何数据和子数据的组合,你就不会说子列表中是否有超过3个元组的元数...  是否可以输入此信息:

[
  [
    {d1, "1"}, 
    {d2, "2"}, 
    {sub_data,
      [
        {d1, "3"},
        {d2, "4"}
      ]
    }
    {d3, "2"}, 
  ], 
  [
    {sub_data,
      [
        {d1, "3"},
      ]
    }
    {d1, "5"},
    {d2, "6"}
  ]
]

预期结果应该是什么?