Hi J—some great questions here, and I'm glad that you're perusing the documentation and getting some evidently great use of it. Let's see if I can't help out with these questions, one by one:
Why is it two? Is it because Depth counts the expression head, “g” as well as the argument “a” as a level?
As I understand it, yes—that's exactly why. Since you've asked specifically for the depth required to write g[a]
(rather than, say, a
), you're getting the level at which g[a]
could first appear, traversing a tree down from the top. The a
inside the g[a]
is indeed one level deeper (at level 3, in u
), but any non-atomic expression will by necessity span multiple levels when asked for in this manner, right? I.e., any non-atomic expression can be represented as head[el,...]
, so if you ask for the Depth
of such an expression, we return the depth corresponding to where that expression could begin, despite the fact that the el
exists one level deeper (and el
could itself be compound, so it could keep going down the tree).
The final example also doesn’t behave as I expect. It says, Level[u, {-2}] results in {g[a], h[a]}, but if we’re starting at the bottom of the TreeForm and proceeding up two levels, why aren’t {f[a], f[a], f[f]} also included? They all have two levels up from the bottom of the TreeForm…
I agree that this is a confusing, and I think it's partly our eyes playing tricks on us because of how TreeForm
represents expressions; I would have guessed the exact same thing that you did. However, there's one clue in your image: what's special about the two branches which were actually returned? They're vertical. Why should that matter? It seems like it shouldn't, but...
Take a look at u
once again. It's:
u=f[f[g[a], a], a, h[a], f]
Notice what's missing: do you see any f[a]
or f[f]
? They don't actually exist in u
; they only exist if you're extracting certain branches within u
. Level
is just telling us which expressions within u
which explicitly exist and have a level of precisely -2
—and that's g[a]
and h[a]
, and nothing else.
Hopefully that's a sufficiently satisfying response! I've asked our tech folks if this understanding is correct, and will update here when I hear back.