3
$\begingroup$

I'm trying to convert the plain path list to the nested tree list like the following codes.

problem = {{"a", "b", "b1", "c1"}, {"a", "b", "b1", "c2"}, {"a", "b", "b1", "c3"}, 
           {"a", "b", "b2"}, {"aa", "b", "b1" }};

answer = {{"a", {"b", {"b1", {"c1", "c2", "c3"}, "b2"}}}, {"aa", {"b", {"b1"}}}}

For reference, I posted the question which is the above answer. (Parsing string with nested information)

My wrong solution using GroupBy and RightFold is

rightFold[fun_, {}, rhs_] := rhs;
rightFold[fun_, {head___, prev_}, rhs_] := rightFold[fun, {head}, fun[prev, rhs]];

re1 = GroupBy[problem, Most -> Last];

kvs = Thread[{Keys[re1], Values[re1]}];
wrong = rightFold[List, #[[1]], #[[2]]] & /@ kvs

wrong is

{{"a", {"b", {"b1", {"c1", "c2", "c3"}}}}, {"a", {"b", {"b2"}}}, {"aa", {"b", b1"}}}

in which "{"a", {"b", {"b2"}}" is not right.

Any suggestions?

$\endgroup$
  • $\begingroup$ Your answer is a little bit inconsistent. Should not it be: { "a", {"b", {"b1", {"c1", "c2", "c3"}, "b2"}}, "aa", {"b", {"b1"}} }? $\endgroup$ – Kuba Jan 20 '15 at 11:13
5
$\begingroup$

This is slightly different from your answer but it is consistent:

ClearAll[h];
h[{{}}] := Sequence[];    
h[list : {{__} ..}] := Normal @ GroupBy[list, First -> Rest, h];

Block[{Rule},
 Rule[x_] := x;
 Rule[x_, y_List] := Sequence[x, y];

 h[problem]
 ]
{"a", {"b", {"b1", {"c1", "c2", "c3"}, "b2"}}, "aa", {"b", {"b1"}}}

This gives exactly the result you need:

ClearAll[h];
h[{{}}] = {};
h[list : {{__} ..}] := Normal @ GroupBy[list, First -> Rest, h];

So the trick is to recursively use h with 3rd argument of GroupBy.

h[problem]

% /. Rule -> (List[#, Join @@ #2] &) /. {} -> Sequence[]
{"a"->{"b"->{"b1"->{"c1"->{}, "c2"->{}, "c3"->{}}, "b2"->{}}}, "aa"->{"b"->{"b1"->{}}}}

{{"a", {"b", {"b1", {"c1", "c2", "c3"}, "b2"}}}, {"aa", {"b", {"b1"}}}}

One could probably use some other function instead of Rest to avoid those replacements at the end. But in that case one will waste time on defining proper DownValues for such function. (it may be usefull to do so maybe)

$\endgroup$
  • $\begingroup$ I am learning so much from your solution, thank you! $\endgroup$ – marsiano Jan 20 '15 at 12:19
  • $\begingroup$ @marsiano I'm learning so much from your question! $\endgroup$ – Kuba Jan 20 '15 at 12:33
  • 3
    $\begingroup$ huh, recursive use of GroupBy. Nice, +1. $\endgroup$ – rcollyer Jan 20 '15 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.