1

有一个可能包含任何内容的术语,例如:

Term1 = [ 
      {"AAA", [ 
               { "K1", "ka1" },
               { "K2", "ka2" }, 
               { "K3", "ka3" } 
              ]
      },
      {"BBB","one"},
      {"CCC", [ 
               { "K1", "kb1" },
               { "K2", "" }, 
               { "K3", "kb3" } 
              ]
      },
      {"DDD", [ 
                [
                 { "K1", "kc1" },
                 { "K2", "kc2" }
                ],
                [
                 { "K1", "kd1" },
                 { "K2", "kd2" }
                ],
                "CACETA",
                123
              ]
      },
      {"EEE", [ 
               { "K1", "kb1" },
               { "K2", 1122  }, 
               { "K3", "kb3" } 
              ]
      },
              { "T1", "T2", "T3" },
              123,
              { "X" },
              [ 1, 2, 3, { "K5", "V5" } ] 
],

我需要生成所有 proplists [{K,V},...] 的列表,例如

[
   { "AAA" , [ ...... ] },
   { "K1"  , "ka1" },
   { "K2" , "ka2" }, 
   ...
   { "BBB" ,"one"},
   { "CCC" , [ ... ] },
   { "K1"  , "kb1" },
   ...
   { "K5", "V5" } 
]
  • 请注意,有些键必须沿着列表重复,它们的值可能是字符串、列表、元组或数字,任何东西。

  • 上例中数据中的最后一项,例如 { "T1", "T2", "T3" } 不应出现在结果中,因为它不是两个项 { K, V} 的 proplist,而是嵌套的{ "K5", "V5" } 是并且应该是结果的一部分。

我查看了这个类似的解决方案并尝试对其进行一些调整,但我的新手 erlang 大脑很难让它与我上面的场景一起工作。

这是我试图用来使其工作的示例,但存在一些错误,与模式匹配相关:

extractPropList( [], ResultList ) -> ResultList;

extractPropList( [H|T], ResultList ) -> extractPropList(T, extractPropList(H, ResultList));

extractPropList( {K,V}, ResultList ) -> [ {K,V} | extractPropList(K, extractPropList(V, ResultList)) ].
4

1 回答 1

1

在测试上述方法时,缺少的部分是处理没有其他匹配项的最后一行(不是列表,不是 {K,V} ):

extractPropLists( [], ResultList ) -> ResultList;
extractPropLists( [H|T], ResultList ) ->    extractPropLists(T, extractPropLists(H, ResultList));
extractPropLists( {K,V}, ResultList ) -> [ {K,V} | extractPropLists(K, extractPropLists(V, ResultList)) ];
extractPropLists( T, ResultList ) -> ResultList.

给定类似于 avove 的数据,我得到的结果在哪里

[{"EEE",[{"K1","kb1"},{"K2",1122},{"K3","kb3"}]},
 {"K3","kb3"},
 {"K2",1122},
 {"K1","kb1"},
 {"DDD",
  [[{"K1","kc1"},{"K2","kc2"}],
   [{"K1","kd1"},{"K2","kd2"}],
   "CACETA",123]},
 {"K2","kd2"},
 {"K1","kd1"},
 {"K2","kc2"},
 {"K1","kc1"},
 {"CCC",[{"K1","kb1"},{"K2","kb2"},{"K3","kb3"}]},
 {"K3","kb3"},
 {"K2","kb2"},
 {"K1","kb1"},
 {"BBB","one"},
 {"AAA",[{"K1","ka1"},{"K2","ka2"},{"K3","ka3"}]},
 {"K3","ka3"},
 {"K2","ka2"},
 {"K1","ka1"}]
于 2013-05-25T12:02:01.023 回答