4
$\begingroup$

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)))))$$

$\endgroup$
  • $\begingroup$ Look up Fold[]. $\endgroup$ – J. M. will be back soon Mar 8 '16 at 15:39
  • $\begingroup$ @J.M. "easily found in the documentation" ?? $\endgroup$ – Mr.Wizard Mar 8 '16 at 15:40
  • 1
    $\begingroup$ @Mr. Wizard, if you put the word "fold" in somewhere, sure… otherwise no. ;) $\endgroup$ – J. M. will be back soon Mar 8 '16 at 15:41
  • $\begingroup$ Related: (7366), (66021) $\endgroup$ – Mr.Wizard Jul 29 '17 at 9:01
7
$\begingroup$

Fold should work for you:

Fold[1 + #2[#1] &, x, Reverse @ {f1, f2, f3, f4}]
1 + f1[1 + f2[1 + f3[1 + f4[x]]]]
$\endgroup$
  • 1
    $\begingroup$ I 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)] $\endgroup$ – Jason B. Mar 8 '16 at 15:41
  • 1
    $\begingroup$ @JasonB If the OP wants to generate this expression for typesetting that will help. If writing a program I would recommend avoiding subscripts. $\endgroup$ – Mr.Wizard Mar 8 '16 at 15:42
  • 1
    $\begingroup$ People like their subscripts, who are we to fight? :-P $\endgroup$ – Jason B. Mar 8 '16 at 15:46
  • $\begingroup$ @Mr-Wizard, can you point me to a post on here where it clearly shows the pitfalls of using Subscript indiscriminately, in a common situation? I don't use it myself, but it was years before I figured out that f[1] was the right substitute for $f_1$. Until then, I was doing ToExpression["f"<>IntegerString[1]] in my loops, which is cumbersome. $\endgroup$ – Jason B. Mar 8 '16 at 15:53
  • 2
    $\begingroup$ @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 Subscript almost entirely for formatting. $\endgroup$ – Mr.Wizard Mar 8 '16 at 15:56
3
$\begingroup$

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

enter image description here

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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