Given a function f and a list {a,b,c,d,e} how can I compactly tell mathematica to return f[a,f[b,f[c,f[d,e]]]]?
It seems that Apply can do the job but I cannot make it work as I want.
Given a function f and a list {a,b,c,d,e} how can I compactly tell mathematica to return f[a,f[b,f[c,f[d,e]]]]?
It seems that Apply can do the job but I cannot make it work as I want.
The function you want to use is Fold which does almost what you want to do i.e.
Fold[f,{a,b,c}]
Out[] := f[f[f[a, b], c], d]
Above operation is called FoldRight in other other languages, because it folds the function from left to the right over the list of arguments.
Your question asks for a FoldLeft which you can easily implement by
fThe former can be achieved by a simple Reverse on the list, the latter by switching the arguments to the function f by defining an anonymous function f[#2,#1]&.
Thus you get your result with
Fold[f[#2, #1] &, Reverse@{a, b, c, d, e}]
Out[]:= f[a, f[b, f[c, f[d, e]]]]
foldLeft[func_,x_,list_]:=Fold[func[#2, #1] &,x, Reverse@list]
– Kvothe
Oct 30 '18 at 14:36
Foldoperation i.e.Fold[f,list]. Check out the documentation, it should be quite straightforward. If you need help you can ask again. – AndreasP Oct 24 '16 at 14:54Fold[f, Reverse@{a, b, c, d, e}]givesf[f[f[f[e, d], c], b], a], while the OP wants the arguments of everyfto be in reversed order. – corey979 Oct 24 '16 at 15:03Fold[f[#2, #1] &, Reverse@{a, b, c, d, e}]– AndreasP Oct 24 '16 at 15:18Functional Iteration– Bob Hanlon Oct 24 '16 at 15:25