In general, when I am learning a new programming language, it helps me to understand how builtin functions works. I am trying to reproduce the builtin Nest[f,exp,n]
without any fancy Mathmatica functions.
This is what I want:
nesting[f_,k_] := Nest[f,#,k]&
=> nesting[f,3][Pi] = f[f[f[Pi]]]
I thought about implementing a recursive function:
nesting[f_,k_] := nesting[f,k-1]
nesting[f,1] := f[#]&
But unfortunately, this does not work. Trying to evaluate the function at some point does add this function evaluation to the outermost, not the innermost function.
=> nesting[f,3][Pi] = f[f[f[#1]&]]][Pi]
It seems that the ampersand (&) from the definition of a pure function has to be outside the whole nested function. That means I want to have following structure:
nesting[f,3] = f[f[f[#1]]]&
For that I tried changing my function definition to
nesting[f_,k_] := nesting[f,k-1]&
nesting[f_,1] := f[#]
This yiedls a (atleast for me) unexpected and definitely unwanted behaviour:
nesting[f,3] = nesting[f,3-1]&
nesting[f,3][Pi] = nesting[f,2-1]&
Why does the second parameter (k) change depending on if I evaluate the function or just want to get the pure function from $3-1$ to $2-1$? And how can I fix my function in general?
nesting[f,1] := f[#]&
Should have an underscore under the first f since it's a function argument. Without it the function only works with literally the symbol "f" $\endgroup$