6
$\begingroup$

Below is the code for applying same head f to all the levels that are indicated

Apply[f, {{{{{a}}}}}, {0, 3}]

Now if we want to apply f to level 0, g to level 1, h to level 2, ..., what would be the simplest form?

$\endgroup$

3 Answers 3

5
$\begingroup$

Using FoldList:

lis = {{{{{a}}}}};
fAt = {{f, 0}, {g, 1}, {h, 2}, {j, 3}};
(res = FoldList[Apply[First@#2, #1, {Last@#2}] &, lis, 
    fAt]) // TableForm

To see the final result only, use Fold instead of FoldList.


enter image description here


Visualization:

TreeForm /@ {lis, res}

enter image description here


Addendum

If you are not comfortable (yet) with using FoldList, then use the following and modify the steps as you see fit:

res2 = lis // Apply[f, #, {0}] & // Apply[g, #, {1}] & // 
   Apply[h, #, {2}] & // Apply[j, #, {3}] &

Last@res == res2

(* True *)
$\endgroup$
3
$\begingroup$

Using MapIndexed:

MapIndexed[{f, g, h, j}[[Length[#2] + 1]] @@ # &, {{{{{a}}}}, {{a}}}, {0, 3}]   

f[g[h[j[{a}]]], g[h[a]]]

$\endgroup$
2
$\begingroup$

Using Fold and Map

 Fold[Map[#2[[1]], #1, #2[[2]]] &, {{{{{a}}}}}, {{f, {0}}, {g, {-1}}}]

f[{{{{{g[a]}}}}}]

$\endgroup$

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.