4
$\begingroup$

We have Map and its upgraded variant MapIndexed. Is there analogy for Nest? I know there is no NestIndexed in Mathematica in recent versions but I mean if it is possible to imitate it by elegant combination of other functions.

My solution with using n++ bellow I do not regard as elegant.

Map[f, {a, b, c, d}]
MapIndexed[f, {a, b, c, d}]

n = 1;
Nest[f[#, n++] &, k, 4]
Clear[n]

(* {f[a], f[b], f[c], f[d]} *)
(* {f[a, {1}], f[b, {2}], f[c, {3}], f[d, {4}]} *)

(* f[f[f[f[k, 1], 2], 3], 4] *)
$\endgroup$
4
  • 1
    $\begingroup$ I don't see using n++ as inelegant - if this were a built-in function it would do something similar $\endgroup$
    – Jason B.
    Dec 2, 2022 at 20:12
  • 2
    $\begingroup$ Maybe Fold[f,k,Range[4]]. Or Nest[{f@@#,#[[2]]+1}&,{k,1},4][[1]]. $\endgroup$
    – user293787
    Dec 2, 2022 at 20:22
  • 1
    $\begingroup$ dang it! just beat me to it @user293787 $\endgroup$
    – lericr
    Dec 2, 2022 at 20:24
  • $\begingroup$ @user293787: That's it! It was something in my mind that was telling me there is a similar function but could not recall it. If there is no better solution I would accept it if you post it as an answer. $\endgroup$ Dec 2, 2022 at 20:28

1 Answer 1

10
$\begingroup$

One could use Fold:

Fold[f,k,Range[4]]
(* f[f[f[f[k,1],2],3],4] *)

Alternatively, one could use Nest using pairs where the first entry contains the evaluations of f and the second entry is the index:

Nest[{f@@#,Last[#]+1}&,{k,1},4][[1]]
(* f[f[f[f[k,1],2],3],4] *)
$\endgroup$
1
  • $\begingroup$ I like the version with Fold. $\endgroup$ Dec 2, 2022 at 20:37

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.