This is probably very easy, but I cannot figure out a way to define a function like: $$ g_h = ( 1 + f_1(1+f_2(1+f_3(.. (1 + f_h)))))$$
Asked
Active
Viewed 315 times
2 Answers
7
Fold should work for you:
Fold[1 + #2[#1] &, x, Reverse @ {f1, f2, f3, f4}]
1 + f1[1 + f2[1 + f3[1 + f4[x]]]]
Mr.Wizard
- 271,378
- 34
- 587
- 1,371
-
1I was about to submit this when your answer showed up. This gives OP's more exactly I think:
g[h_] := Fold[1 + Subscript[f, #2][#1] &, 1 + Subscript[f, h], Reverse@Range@(h - 1)]– Jason B. Mar 08 '16 at 15:41 -
1@JasonB If the OP wants to generate this expression for typesetting that will help. If writing a program I would recommend avoiding subscripts. – Mr.Wizard Mar 08 '16 at 15:42
-
1
-
@Mr-Wizard, can you point me to a post on here where it clearly shows the pitfalls of using
Subscriptindiscriminately, in a common situation? I don't use it myself, but it was years before I figured out thatf[1]was the right substitute for $f_1$. Until then, I was doingToExpression["f"<>IntegerString[1]]in my loops, which is cumbersome. – Jason B. Mar 08 '16 at 15:53 -
2@JasonB point #3 in (18395) is the first thing that comes to mind. Perhaps there is more. I simply know that many experienced users have cautioned against this, and early in the process of learning Mathematica I had a number of problems which I later traced to the use of subscripts. As a result I reserve
Subscriptalmost entirely for formatting. – Mr.Wizard Mar 08 '16 at 15:56
3
So the way to get exactly what is written is
g[h_] := Fold[1 + Subscript[f, #2][#1] &, 1 + Subscript[f, h], Reverse@Range@(h - 1)]
so that
g[5]
gives
But as is pointed out all the time here, you should avoid subscripts. Anytime you want to use $f_i$, you should use f[i] instead. So in this case what you need is
g[h_] :=
Fold[1 + f[#2][#1] &, 1 + f[h], Reverse@Range@(h - 1)]
g[5]
(* 1 + f[1][1 + f[2][1 + f[3][1 + f[4][1 + f[5]]]]] *)
Less readable, but now you don't have to worry about what a DownValue of Subscript is.
Jason B.
- 68,381
- 3
- 139
- 286

Fold[]. – J. M.'s missing motivation Mar 08 '16 at 15:39