7

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.

corey979
  • 23,947
  • 7
  • 58
  • 101
tst
  • 953
  • 6
  • 13
  • 1
    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. – AndreasP Oct 24 '16 at 14:54
  • Ah, yes! I knew that there should be a way, I didn't know how it was called. Thanks! – tst Oct 24 '16 at 14:56
  • @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. – corey979 Oct 24 '16 at 15:03
  • No worries, in my case the arguments of f commute. Through work. – tst Oct 24 '16 at 15:04
  • 4
    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}] – AndreasP Oct 24 '16 at 15:18
  • 1

1 Answers1

12

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

  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]]]]
AndreasP
  • 598
  • 4
  • 10
  • An explicit definition for foldLeft: foldLeft[func_,x_,list_]:=Fold[func[#2, #1] &,x, Reverse@list] – Kvothe Oct 30 '18 at 14:36