0
$\begingroup$

I'm looking for a function that gives the depth of nested lists in an expression. I do not want to include contributions from things like f[1]. Depth does do this. Note Depth[{f}] != Depth[{f[1]}]. Does this exist or does someone have a good function for this.


My attempt:

depth := Depth[# //. f_[__] /; ! f === List -> f] &

but I'm sure someone more experienced can do better. (I'm probably forgetting many cases where this would not give the desired result.)

$\endgroup$
2
  • 2
    $\begingroup$ What about lists inside other heads? Could you give couple of examples and desired results? $\endgroup$
    – Kuba
    Jun 15, 2017 at 9:23
  • $\begingroup$ @Kuba, Yes well spotted. For the current thing I'm using it for I don't have lists inside arguments, so I'm safe. I guess it's not that clear what the desired result would be in that instance (which also explains why such a function is not included in Mathematica). Both the option of excluding and including these lists in the count seem like a valid option and an interesting function. Excluding these is more likely to be what I might need in the near future. I guess I'd accept either (or the best would be both) as an answer. $\endgroup$
    – Kvothe
    Jun 15, 2017 at 10:24

1 Answer 1

2
$\begingroup$

If you dont want to count lists in the arguments, you can use the following recursive definition:

ClearAll[depth];
depth[{}] := 2;
depth[list_List] := 1 + Max[Map[depth, list]];
depth[_] := 1;

Testing:

depth[{f}]

2

depth[{f[a]}]

2

depth[{f[{a}]}]

2

depth[{f[a], {{f[b]}}}]

4

$\endgroup$
0

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.