2
$\begingroup$

I was studying some functions for list manipulation and I have some doubts about the difference between indice, depth and level in an expression. For example, in the detail of DeleteCases there is this:

A positive level n consists of all parts of expr specified by n indices.
A negative level -n consists of all parts of expr with depth n.

Can someone explain me what is the difference between these three concepts, an in particular what is the meaning of those details of DeleteCases function.

$\endgroup$
1
$\begingroup$

Hopefully, this illustration makes everything more clear:

ClearAll[a, b, c, d, e, f, g];
expr = 1 + 2 a + c d + e/f + g^h;
TreeForm[expr]

enter image description here

Now let's looks at positive levels (we use function Level which gives subexpressions at a given level):

Table[Level[expr, {i}], {i, 1, 3}] // Column
(*
{
 {{1, 2 a, c d, e/f, g^h}},
 {{2, a, c, d, e, 1/f, g, h}},
 {{f, -1}}
}
*)

As you can see, at the first level, we have all the individual summands (everything that "starts" at the second line of the treeform), at the second level we only have everything that "starts" at the third line of treeform, etc.).

Compare this to negative levels:

Table[Level[expr, {-i}], {i, 1, 3}] // Column
(*
{
 {{1, 2, a, c, d, e, f, -1, g, h}},
 {{2 a, c d, 1/f, g^h}},
 {{e/f}}
}
*)

At the -1 level, it's all the leaves; at the -2 level, it's everything that you can get traversing up from the leaves, etc.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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