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


1 Answer 1


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

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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