Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question is similar to Numbering nested list according with Depth (or Level)

I have a list like

list = {"A" -> {"a1", "a2"}, "B" -> {"b1"->{"z1","z2"},"b2" -> {"z3","z4"}},"C" -> {"c1" -> {"cc1"-> {"x","y"}, "cc2" -> {"x1", "x2"}},"c2" -> {"xx", "yy"}, "c3" ->{"u","v", "w"}}};

And I would like to build a function that help me navigate it, according to the depth, like in

Navigate[list,1] = {"A","B","C"}
Navigate[list,2] = {"A" -> {"a1", "a2"},  "B" -> {"b1", "b2"}, "C" -> {"c1", "c2", "c3"}}
Navigate[list,3] = {"A" -> {"a1", "a2"},  "B" -> {"b1" -> {"z1","z2"}, "b2" -> {"z3","z4"}}, "C" -> {"c1" -> {"cc1","cc2"}, "c2" ->{"xx", "yy"}, "c3" ->{"u","v", "w"}}}

and so on.

By hands I have a solution for small depth, but since the list can be arbitrary nested I think I need a nested approach

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Here's a recursive function that seems to do what you ask:

ClearAll[navigate];
Attributes[navigate] = {Listable};
navigate[rule_Rule, 1] := First@rule;
navigate[rule_Rule, k_] := Rule[(First@rule), navigate[Last@rule, k - 1]];
navigate[notrule_, k_] := notrule;

Note that your notion of depth doesn't match Mathematica's notion of depth. In Mathematica the left- and right-hand sides of a rule are at the same depth. You consider the left to be higher than the right. So the function above is all about fiddling with rules.

First off we set it to be Listable. This just makes the function automatically apply to each element of a list separately without us having to do anything.

Next we take depth 1 to just be the left-hand side of a rule, or the whole thing if it is not a rule.

For deeper levels we take the left-hand side of a rule, and make a new rule to a recursed version of the right-hand side. Again, anything that is not a rule is just left alone.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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