1
$\begingroup$

I am not sure to really understand how the function Apply works at level 2 for example.

I have read this question and few others and it doesn't help me :Levels: how do they work?

Take the following example :

liste5 = Array[m, {2, 2, 2}]

{{{m[1, 1, 1], m[1, 1, 2]}, {m[1, 2, 1], m[1, 2, 2]}}, {{m[2, 1, 1], 
   m[2, 1, 2]}, {m[2, 2, 1], m[2, 2, 2]}}}

liste5 // TreeForm

Here is the Tree that shows up in mathematica. I added the numbers of the level on the left.

enter image description here

I want to apply a function at level 2 :

Apply[fonction, liste5, {2}]

{{fonction[m[1, 1, 1], m[1, 1, 2]], fonction[m[1, 2, 1], m[1, 2, 2]]}, {fonction[m[2, 1, 1], m[2, 1, 2]], fonction[m[2, 2, 1], m[2, 2, 2]]}}


What I don't understand :

From what I understood, apply goes at level 2 of the tree, and replace the Head there by the function "fonction". So in practice in this example I would have 4 trees where I replace their heads by "fonction" and I return the whole in a list.

Thus, the result should be :

{fonction @@ liste5[[1, 1]], fonction @@ liste5[[1, 2]], 
 fonction @@ liste5[[2, 1]], fonction @@ liste5[[2, 2]]}

{fonction[m[1, 1, 1], m[1, 1, 2]], fonction[m[1, 2, 1], m[1, 2, 2]], 
 fonction[m[2, 1, 1], m[2, 1, 2]], fonction[m[2, 2, 1], m[2, 2, 2]]}

However, it is not the case.

Said differently, why do I have a 2 dimensional list as a result and not a 1 dimensional one ? Why are the two first branch of level 2 "regrouped" together in a way ?

$\endgroup$

1 Answer 1

1
$\begingroup$

Apply respects the tree structure and just replaces the heads. A view at the TreeForm of the expressions reveals quite quickly what happens:

liste5 // TreeForm

enter image description here

Apply[fonction, liste5, {2}] // TreeForm

enter image description here

$\endgroup$
1
  • $\begingroup$ Allright, so the thing is : I go at level 2, I consider the 4 trees. I replace their Heads by function and then I reconstruct the whole having the same structure has the original tree. Thanks ! $\endgroup$
    – StarBucK
    Dec 30, 2018 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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