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.

  • 1
    $\begingroup$ What you want to do is best expressed by a Fold operation i.e. Fold[f,list]. Check out the documentation, it should be quite straightforward. If you need help you can ask again. $\endgroup$
    – AndreasP
    Commented Oct 24, 2016 at 14:54
  • $\begingroup$ Ah, yes! I knew that there should be a way, I didn't know how it was called. Thanks! $\endgroup$
    – tst
    Commented Oct 24, 2016 at 14:56
  • $\begingroup$ @AndreasP It's not that straightforward: Fold[f, Reverse@{a, b, c, d, e}] gives f[f[f[f[e, d], c], b], a], while the OP wants the arguments of every f to be in reversed order. $\endgroup$
    – corey979
    Commented Oct 24, 2016 at 15:03
  • 4
    $\begingroup$ Thanks for the correction @corey979, I didn't look at the question that closely, my bad. For completions sake, this'd work: Fold[f[#2, #1] &, Reverse@{a, b, c, d, e}] $\endgroup$
    – AndreasP
    Commented Oct 24, 2016 at 15:18
  • 1
    $\begingroup$ A useful guide is Functional Iteration $\endgroup$
    – Bob Hanlon
    Commented Oct 24, 2016 at 15:25

1 Answer 1


The function you want to use is Fold which does almost what you want to do i.e.

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

  1. Reversing the inputlist
  2. Reversing the argument-order of f

The 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]]]]
  • $\begingroup$ An explicit definition for foldLeft: foldLeft[func_,x_,list_]:=Fold[func[#2, #1] &,x, Reverse@list] $\endgroup$
    – Kvothe
    Commented Oct 30, 2018 at 14:36

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.