WolframLang: Level Spec (Tree Depth)
Tree Depth
An expression forms a tree, and it has depth levels.
E.g. Flat tree, has depth 1. All subexpressions are in level 1.
TreeForm[ {1,2,3} ]
Here's a tree, with 2 levels of depth. Some subexpressions are in level 1, some in level 2.
TreeForm[ {1, 2, {a, b}} ]
here's a more complex tree, with 3 levels of depth.
TreeForm[{0, {a, {b, c}}, {{3}, 1}, f[x, y]}]
each element or sub-expression lies in a specific level depth.
Level Spec
level spec is a standard form in WolframLang to specify a specific level of a tree, or a range of levels m to n.
the syntax looks like this:
{n}
→ only level n.{-n}
→ negative level means count starting from leafs.{-1}
means all leafs.{m,n}
→ levels m to n. The second part can beInfinity
.
many functions take an optional argument of level spec.
e.g.
Map
,
Position
,
Cases
,
etc.
Examples of Level Spec
the function Map
takes a third argument for level spec.
〔see WolframLang: Map Function to List〕
Map[ f, {a, {b, {c , d}}} , {0}] (* f[{a, {b, {c, d}}}] *) Map[ f, {a, {b, {c , d}}} , {1}] (* {f[a], f[{b, {c, d}}]} *) Map[ f, {a, {b, {c , d}}} , {2}] (* {a, {f[b], f[{c, d}]}} *) Map[ f, {a, {b, {c , d}}} , {3}] (* {a, {b, {f[c], f[d]}}} *) Map[ f, {a, {b, {c , d}}} , {-1}] (* {f[a], {f[b], {f[c], f[d]}}} *) Map[ f, {a, {b, {c , d}}} , {-2}] (* {a, {b, f[{c, d}]}} *)
Map[ f, {a, {b, {c , d}}} , {1, Infinity}] (* {f[a], f[{f[b], f[{f[c], f[d]}]}]} *) Map[ f, {a, {b, {c , d}}} , {0, Infinity}] (* f[{f[a], f[{f[b], f[{f[c], f[d]}]}]}] *)
Level Spec is Critical in Matching Nested Patterns
levelspec is especially important in pattern matching, because any pattern that has nested expression means it has depth 2 or more, and it may match a given expression at multiple range of levels of depth.
more examples: