5
$\begingroup$

I would like to apply a function f recursively to an expression expr an arbitrary number of times. However the catch is that f also takes a parameter i and I want it to change with each application. So applied once should look like f[1][expr].

Concretely what I want, should look like this:

f[5][
   f[4][
      f[3][
         f[2][
            f[1][expr] ]]]]

It seems to me this should be easy somehow, but I don't know how to leverage functions like Nest, Do or Fold in such a way that they produce this.

$\endgroup$

1 Answer 1

5
$\begingroup$

Fold

Fold[f[#2][#] &, expr, Range[5]]

f[5][f[4][f[3][f[2][f[1][expr]]]]]

Fold[#2 @ # &, expr, f/@ Range[5]]

f[5][f[4][f[3][f[2][f[1][expr]]]]]

Nest

Module[{i = 1}, Nest[f[i++]@# &, expr, 5]]

f[5][f[4][f[3][f[2][f[1][expr]]]]]

Composition

Composition[## & @@ (f /@ Reverse[Range@5])]@ expr

f[5][f[4][f[3][f[2][f[1][expr]]]]]

(Composition @@ f /@ Reverse[Range@5]) @ expr

f[5][f[4][f[3][f[2][f[1][expr]]]]]

Compose

Compose[## & @@ (f /@ Reverse[Range@5]), expr]

f[5][f[4][f[3][f[2][f[1][expr]]]]]

$\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.