WolframLang: Level Spec (Tree Depth)

By Xah Lee. Date: .

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} ]

WolframLang level spec 2024 hJmFY
WolframLang level spec 2024 hJmFY

Here's a tree, with 2 levels of depth. Some subexpressions are in level 1, some in level 2.

TreeForm[ {1, 2, {a, b}} ]

WolframLang level spec 2024 Fy9Yp
WolframLang level spec 2024 Fy9Yp

here's a more complex tree, with 3 levels of depth.

TreeForm[{0, {a, {b, c}}, {{3}, 1}, f[x, y]}]

WolframLang level spec 2024-08-20 Dn3WC
WolframLang level spec 2024-08-20 Dn3WC

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:

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:

WolframLang, Tree Depth and Level Spec

WolframLang List